std::thread pass by reference calls copy constructor

冷暖自知 提交于 2019-11-26 14:40:26

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));

Obviously you must make sure that logger outlives the thread.

I get a compiler error when I try to pass the logger (or the socket) to the thread by reference

It is not sufficient for the thread's entrypoint function to take a reference type: the thread object itself takes its arguments by value. This is because you usually want a copy of objects in a separate thread.

To get around this, you may pass std::ref(logger), which is a reference wrapper hiding reference semantics under a copyable object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!