当给 thread 的执行函数传递指针参数时,没有任何问题,但是如果想传递引用,按照普通函数的调用方法会遇到编译失败:
#include <iostream>
#include <thread>
#include <string> int main()
{
std::string a("Hello");
std::cout << "address = " << &a << "\n";
std::thread t([](std::string& a)
{
std::cout << "in thread address = " << &a << "\n";
}, a);
t.join();
}
编译:g++ -std=c++11 -pthread test.cpp
失败了:
In file included from /usr/include/c++/4.7/bits/move.h::,
from /usr/include/c++/4.7/bits/stl_pair.h:,
from /usr/include/c++/4.7/bits/stl_algobase.h:,
from /usr/include/c++/4.7/bits/char_traits.h:,
from /usr/include/c++/4.7/ios:,
from /usr/include/c++/4.7/ostream:,
from /usr/include/c++/4.7/iostream:,
from test.cpp::
/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::: required from ?.lass std::result_of<main()::<lambda(std::string&)>(std::basic_string<char>)>?
/usr/include/c++/4.7/functional::: required from ?.truct std::_Bind_simple<main()::<lambda(std::string&)>(std::basic_string<char>)>?
/usr/include/c++/4.7/thread::: 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::: required from here
/usr/include/c++/4.7/type_traits::: error: no match for call to ?.main()::<lambda(std::string&)>) (std::basic_string<char>)?
test.cpp::: note: candidates are:
In file included from /usr/include/c++/4.7/bits/move.h::,
from /usr/include/c++/4.7/bits/stl_pair.h:,
from /usr/include/c++/4.7/bits/stl_algobase.h:,
from /usr/include/c++/4.7/bits/char_traits.h:,
from /usr/include/c++/4.7/ios:,
from /usr/include/c++/4.7/ostream:,
from /usr/include/c++/4.7/iostream:,
from test.cpp::
/usr/include/c++/4.7/type_traits::: note: void (*)(std::string&) {aka void (*)(std::basic_string<char>&)} <conversion>
/usr/include/c++/4.7/type_traits::: note: candidate expects arguments, provided
test.cpp::: note: main()::<lambda(std::string&)>
test.cpp::: note: no known conversion for argument from ?.td::basic_string<char>?.to ?.td::string& {aka std::basic_string<char>&}?
这里类似于 std::bind,std::thread 和 std::bind 采用了相同的机制,必须使用 std::ref 来包装:
#include <iostream>
#include <thread>
#include <string> int main()
{
std::string a("Hello");
std::cout << "address = " << &a << "\n";
std::thread t([](std::string& a)
{
std::cout << "in thread address = " << &a << "\n";
}, std::ref(a));
t.join();
}