I was experimenting with std::async
and ended up with a code that looks like that :
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;
}
and the result is :
new obj
delete obj
delete obj
delete obj
5
delete obj
delete obj
delete obj
I then tried to change void foo(obj a)
by void foo(obj &a)
:
new obj
delete obj
delete obj
delete obj
5
delete obj
delete obj
Why would 5 copies of my object be made for this simple code? I have to admit, I'm really confused. Would someone care to explain this?
Edit
I'm using VS2012