当给 thread 的执行函数传递指针参数时,没有任何问题,但是如果想传递引用,按照普通函数的调用方法会遇到编译失败:
1 #include <iostream> 2 #include <thread> 3 #include <string> 4 5 int main() 6 { 7 std::string a("Hello"); 8 std::cout << "address = " << &a << " "; 9 std::thread t([](std::string& a) 10 { 11 std::cout << "in thread address = " << &a << " "; 12 }, a); 13 t.join(); 14 }
编译:g++ -std=c++11 -pthread test.cpp
失败了:
In file included from /usr/include/c++/4.7/bits/move.h:57:0, from /usr/include/c++/4.7/bits/stl_pair.h:61, from /usr/include/c++/4.7/bits/stl_algobase.h:65, from /usr/include/c++/4.7/bits/char_traits.h:41, from /usr/include/c++/4.7/ios:41, from /usr/include/c++/4.7/ostream:40, from /usr/include/c++/4.7/iostream:40, from test.cpp:1: /usr/include/c++/4.7/type_traits: In instantiation of ?.truct std::_Result_of_impl<false, false, main()::<lambda(std::string&)>, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >?. /usr/include/c++/4.7/type_traits:1857:12: required from ?.lass std::result_of<main()::<lambda(std::string&)>(std::basic_string<char>)>? /usr/include/c++/4.7/functional:1563:61: required from ?.truct std::_Bind_simple<main()::<lambda(std::string&)>(std::basic_string<char>)>? /usr/include/c++/4.7/thread:133:9: required from ?.td::thread::thread(_Callable&&, _Args&& ...) [with _Callable = main()::<lambda(std::string&)>; _Args = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >&}]? test.cpp:12:7: required from here /usr/include/c++/4.7/type_traits:1834:9: error: no match for call to ?.main()::<lambda(std::string&)>) (std::basic_string<char>)? test.cpp:9:17: note: candidates are: In file included from /usr/include/c++/4.7/bits/move.h:57:0, from /usr/include/c++/4.7/bits/stl_pair.h:61, from /usr/include/c++/4.7/bits/stl_algobase.h:65, from /usr/include/c++/4.7/bits/char_traits.h:41, from /usr/include/c++/4.7/ios:41, from /usr/include/c++/4.7/ostream:40, from /usr/include/c++/4.7/iostream:40, from test.cpp:1: /usr/include/c++/4.7/type_traits:1834:9: note: void (*)(std::string&) {aka void (*)(std::basic_string<char>&)} <conversion> /usr/include/c++/4.7/type_traits:1834:9: note: candidate expects 2 arguments, 2 provided test.cpp:9:33: note: main()::<lambda(std::string&)> test.cpp:9:33: note: no known conversion for argument 1 from ?.td::basic_string<char>?.to ?.td::string& {aka std::basic_string<char>&}?
这里类似于 std::bind,std::thread 和 std::bind 采用了相同的机制,必须使用 std::ref 来包装:
1 #include <iostream> 2 #include <thread> 3 #include <string> 4 5 int main() 6 { 7 std::string a("Hello"); 8 std::cout << "address = " << &a << " "; 9 std::thread t([](std::string& a) 10 { 11 std::cout << "in thread address = " << &a << " "; 12 }, std::ref(a)); 13 t.join(); 14 }