std::thread 通过引用调用复制构造函数

时间:2022-12-07
本文介绍了std::thread 通过引用调用复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我在使用 std::thread 将数据传递到线程时遇到了问题.我以为我了解复制构造函数等的一般语义,但似乎我不太明白这个问题.我有一个名为 Log 的简单类,它因此隐藏了它的复制构造函数:

Well I have an issue with passing data into a thread using std::thread. I thought I understood the general semantics of copy constructors, etc. but it seems I don't quite grasp the problem. I have a simple class called Log that has hidden it's copy constructor thusly:

class Log
{
public:
    Log(const char filename[], const bool outputToConsole = false);
    virtual ~Log(void);

    //modify behavior
    void appendStream(std::ostream *);
    //commit a new message
    void commitStatus(const std::string str);

private:
    //members
    std::ofstream fileStream;
    std::list<std::ostream *> listOfStreams;

    //disable copy constructor and assignment operator
    Log(const Log &);
    Log & operator=(const Log &);
}

现在我有一个主要基于 http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/example/cpp11/echo/blocking_tcp_echo_server.cpp

now I have a main based heavily on http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/example/cpp11/echo/blocking_tcp_echo_server.cpp

int main()
{
    static int portNumber = 10000;

    Log logger("ServerLog.txt", true);
    logger.commitStatus("Log Test String");

    try {
        boost::asio::io_service ioService;
        server(ioService, portNumber, logger);
    }
    catch (std::exception &e)
    {
        std::cerr << "Exception " << e.what() << std::endl;
        logger.commitStatus(e.what());
    }

    return 0;
}

可以看到main调用了函数server,传递了IOService、portNumber和logger.记录器是通过引用传递的,因此:

You can see that main calls the function server and passes the IOService, portNumber and logger. The logger is passed by reference, thusly:

using boost::asio::ip::tcp;

void server(boost::asio::io_service &ioService, unsigned int port, Log &logger)
{
    logger.commitStatus("Server Start");

    tcp::acceptor acc(ioService, tcp::endpoint(tcp::v4(), port));

    while(true)
    {
        tcp::socket sock(ioService);
        acc.accept(sock);

        std::thread newThread(session, &sock, logger);
        newThread.detach();
    }

    logger.commitStatus("Server closed");
}

当我尝试通过引用将记录器(或套接字)传递给线程时出现编译器错误,但通过引用将它传递给 session() 时我没有收到错误

I get a compiler error when I try to pass the logger (or the socket) to the thread by reference, but I do not get the error when passing it to the session() by reference

static void session(tcp::socket *sock, Log &logger)
{
    std::cout << " session () " << std::endl;
}

现在我认为我正确理解了引用与传递指针相同.也就是说,它不调用复制构造函数,它只是传递指针,它让您在语法上将其视为不是指针.

Now I thought that I understood correctly that a reference is the same as passing a pointer. That is, it does not call the copy constructor, it simply passes the pointer, which it lets you syntactically treat like it's not a pointer.

错误 C2248:'Log::Log':无法访问类 'Log' 中声明的私有成员

error C2248: 'Log::Log' : cannot access private member declared in class 'Log'

1> log.h(55) : 见 'Log::Log' 的声明

1> log.h(55) : see declaration of 'Log::Log'

1> log.h(28) : 见 'Log' 的声明

1> log.h(28) : see declaration of 'Log'

...

:参见正在编译的函数模板实例化'std::thread::thread(_Fn,_V0_t &&,_V1_t)'的参考

: see reference to function template instantiation 'std::thread::thread(_Fn,_V0_t &&,_V1_t)' being compiled

1> 与

1> [

1> Fn=void (_cdecl *)(boost::asio::ip::tcp::socket *,Log &),

1> Fn=void (_cdecl *)(boost::asio::ip::tcp::socket *,Log &),

1> _V0_t=boost::asio::ip::tcp::socket *,

1> _V0_t=boost::asio::ip::tcp::socket *,

1> _V1_t=日志 &

1> _V1_t=Log &

1>]

但是如果我修改它来传递一个指针,一切都会很开心

However if I modify it to pass a pointer, everything is happy

...
        std::thread newThread(session, &sock, &logger);
...

static void session(tcp::socket *sock, Log *logger)
{
    std::cout << " session () " << std::endl;
}

为什么通过引用传递调用我的复制构造函数.由于std::thread,这里有什么特别的事情发生吗?我是否误解了复制构造函数并通过引用传递?

Why is passing by reference calling my copy constructor. Is there something special happening here because of std::thread? Did I misunderstand the copy constructor and pass by reference?

如果我像示例中那样尝试使用 std::move() ,我会得到一个不同但同样令人困惑的错误.我的 VS2012 是否可能没有正确实现 C++11?

I get a different but equally baffling error if I try to use std::move() as it is done in the example. Is it possible my VS2012 is not implementing C++11 correctly?

推荐答案

std::thread 按值接受其参数.你可以通过使用 std::reference_wrapper:

std::thread takes its arguments by value. You can get reference semantics back by using std::reference_wrapper:

std::thread newThread(session, &sock, std::ref(logger));

显然,您必须确保 logger 比线程寿命更长.

Obviously you must make sure that logger outlives the thread.

这篇关于std::thread 通过引用调用复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:为什么从`std::async` 阻塞返回未来的析构函数? 下一篇:如何检查 std::thread 是否仍在运行?

相关文章

最新文章