我正在试验std::async
并最终得到一个看起来像这样的代码:
class obj {
public:
int val;
obj(int a) : val(a) {
cout << "new obj" << endl;
}
~obj() {
cout << "delete obj" << endl;
}
};
void foo(obj a) {
this_thread::sleep_for(chrono::milliseconds(500));
cout << a.val << endl;
}
int main(int argc, int **args) {
obj a(5);
auto future = async(foo, a);
future.wait();
return 0;
}
结果是:
new obj
delete obj
delete obj
delete obj
5
delete obj
delete obj
delete obj
然后我尝试void foo(obj a)
通过以下方式进行更改void foo(obj &a)
:
new obj
delete obj
delete obj
delete obj
5
delete obj
delete obj
为什么要为这个简单的代码制作我的对象的 5 个副本?我不得不承认,我真的很困惑。有人愿意解释一下吗?
编辑
我正在使用 VS2012