See code snippet below:
class A {
public:
A() {
std::cout << "A is constructed" << std::endl;
}
~A() {
std::cout << "A is destroyed" << std::endl;
}
};
static void foo( A a ) {
std::cout << "inside foo" << std::endl;
}
int _tmain(int argc, _TCHAR* argv[]) {
A a;
std::thread( foo, a ).detach();
std::this_thread::sleep_for( std::chrono::seconds( 2 ) );
return 0;
}
The console output that I see is:
A is constructed
inside foo
A is destroyed
A is destroyed
A is destroyed
A is destroyed
A is destroyed
A is destroyed
Press any key to continue . . .
I create an instance of A and then try to pass it into a new thread. I pause my main thread for 2 seconds and then I quit. Why is the A destructor called so many times, but the constructor is only called once?
I should mention that I'm using VS2013 on Windows 7.