《C++ Concurrency in Action》笔记2 线程函数传参(2)

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()。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值