问题描述
这是示例:
#include<iostream>
#include<thread>
using namespace std;
void f1(double& ret) {
ret=5.;
}
void f2(double* ret) {
*ret=5.;
}
int main() {
double ret=0.;
thread t1(f1, ret);
t1.join();
cout << "ret=" << ret << endl;
thread t2(f2, &ret);
t2.join();
cout << "ret=" << ret << endl;
}
输出为:
ret=0
ret=5
编译gcc 4.5.2,有和没有-O2
Compiled with gcc 4.5.2, with and without -O2
这是预期的行为吗?
谢谢
推荐答案
std :: thread
推导出参数类型并按值存储。
The constructor of std::thread
deduces argument types and stores them by value.
C ++模板函数参数类型推导机制从类型 T&
的参数中键入 T
。因此, std :: thread
的所有参数都通过值传递,所以 f1()
和 f2()
总是得到一个副本。
C++ template function argument type deduction mechanism deduces type T
from an argument of type T&
. Hence, all arguments to std::thread
are passed by value so that f1()
and f2()
always get a copy.
如果你坚持使用引用,请使用 boost :: ref()
或 std :: ref()
:
If you insist on using a reference, wrap the argument using boost::ref()
or std::ref()
:
thread t1(f1, boost::ref(ret));
或者,如果你喜欢简单,传递一个指针。这是为你后面的 boost :: ref()
或 std :: ref()
Or, if you prefer simplicity, pass a pointer. This is what boost::ref()
or std::ref()
do for you behind the scene.
这篇关于指针和引用之间的差异作为线程参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!