help passing class into std::thread arguments

Started by
2 comments, last by mmakrzem 8 years, 5 months ago

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.

Advertisement
It appears that you're passing your As by value. At least some of the extra destructor invocations come from the copies being destroyed. If you were to define a copy constructor that logged the way your constructor does, you would see the copies being created as well as destroyed.

Yup. More specifically, your class actually looks like:


class A {
public:
   A() {
      std::cout << "A is constructed" << std::endl;
   }

   // Copy constructor generated automatically by compiler
   A(const A &a) {
   }

   ~A() {
      std::cout << "A is destroyed" << std::endl;
   }
};
Right, I forgot about the default copy constructor

This topic is closed to new replies.

Advertisement