std::ref的作用是声明要传递的参数是以引用的方式传递的。
先看下面的程序:
namespace mparam2
{
class A
{
public:
A(const string &s) :str(s) {}
A(const A &other)
{
cout << "cur thread id:" << this_thread::get_id() << ":" << "A::A()" << endl;
str = other.str;
}
string str;
};
void f(A &a)
{
cout << "sub thread id:" << this_thread::get_id() << endl;
a.str = "new string";
}
void call_by_main()//被main函数调用
{
cout << "main thread id:" << this_thread::get_id() << endl;
A a("old string");
thread t(f, a);
t.join();
cout << "after thread:" << a.str << endl;
}
}
输出为:
main thread id:16260
cur thread id:16260:A::A()
sub thread id:1984
after thread:old string
请按任意键继续. . .
如果将thread t(f, a)改为thread t(f, std::ref(a)),则输出为:
main thread id:15880
sub thread id:13388
after thread:new string
请按任意键继续. . .
结论:
1.在创建线程时,即使线程函数指定的参数为引用,如果不加std::ref(),那么仍然会执行参数拷贝。
2.拷贝是在父线程中执行的。
3.如果需要传递引用则需要对参数明确执行std::ref()。