問題描述
為什么在創建 std::thread
時不能通過引用傳遞對象?
Why can't you pass an object by reference when creating a std::thread
?
例如下面的代碼段給出了一個編譯錯誤:
For example the following snippit gives a compile error:
#include <iostream>
#include <thread>
using namespace std;
static void SimpleThread(int& a) // compile error
//static void SimpleThread(int a) // OK
{
cout << __PRETTY_FUNCTION__ << ":" << a << endl;
}
int main()
{
int a = 6;
auto thread1 = std::thread(SimpleThread, a);
thread1.join();
return 0;
}
錯誤:
In file included from /usr/include/c++/4.8/thread:39:0,
from ./std_thread_refs.cpp:5:
/usr/include/c++/4.8/functional: In instantiation of ‘struct std::_Bind_simple<void (*(int))(int&)>’:
/usr/include/c++/4.8/thread:137:47: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(int&); _Args = {int&}]’
./std_thread_refs.cpp:19:47: required from here
/usr/include/c++/4.8/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<void (*(int))(int&)>’
typedef typename result_of<_Callable(_Args...)>::type result_type;
^
/usr/include/c++/4.8/functional:1727:9: error: no type named ‘type’ in ‘class std::result_of<void (*(int))(int&)>’
_M_invoke(_Index_tuple<_Indices...>)
^
我已改為傳遞指針,但有更好的解決方法嗎?
I've changed to passing a pointer, but is there a better work around?
推薦答案
使用 reference_wrapper
使用 std::ref
:
Explicitly initialize the thread with a reference_wrapper
by using std::ref
:
auto thread1 = std::thread(SimpleThread, std::ref(a));
(或 std::cref
而不是 std::ref
,視情況而定).根據 cppreference on std:thread
的注釋:
(or std::cref
instead of std::ref
, as appropriate). Per notes from cppreference on std:thread
:
線程函數的參數按值移動或復制.如果需要將引用參數傳遞給線程函數,則必須對其進行包裝(例如使用 std::ref
或 std::cref
).
The arguments to the thread function are moved or copied by value. If a reference argument needs to be passed to the thread function, it has to be wrapped (e.g. with
std::ref
orstd::cref
).
這篇關于在 C++11 中通過引用 std::thread 傳遞對象的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!