Jump to content
  • Advertisement
Sign in to follow this  
mmakrzem

help passing class into std::thread arguments

This topic is 1067 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Edited by MarekKnows.com

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

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;
   }
};

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!