[英]Difference Between Pointer(*) And Reference(&)
我在这里使用Reference(&),但是a并没有改变。为什么? 当我使用Pointer(*)时,值已更改。
int all=0;
void call_from_thread(int & a)
{
a = 5;
}
int main()
{
thread s = thread(call_from_thread, all);
s.join();
return 0;
}
另一个程序,在这种情况下,我也使用Reference(&),但是值已更改。 为什么线程中的值a不变?
void Func3(int &x)
{
x = x + 10;
}
int main() {
int n = 0;
Func3(n);
cout << “n = ” << n << endl; // n = 10
}
std::thread
构造函数在线程创建步骤期间复制其参数。...普通引用无法在旅途中幸存,并且call_from_thread
函数接收对该副本的引用。
可以在标准中找到详细信息。 thread::thread
构造函数的行为描述为
构造一个线程类型的对象。 新的执行线程执行
INVOKE(DECAY_COPY(std::forward<F>(f)), DECAY_COPY(std::forward<Args>(args))...)
,并在构造线程中评估对DECAY_COPY
的调用。
DECAY_COPY
的确切定义非常复杂,但是顾名思义,它会忽略引用并创建值副本。
一个简单的解决方法是使用std::ref
。
thread s = thread(call_from_thread, std::ref(all));
这将使指针保持在副本中,并且仅在绑定引用参数时解析为实际目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.