c++ - Undesirable destructor call when starting a thread on a member function -
i have event loop in main function, in create object , run thread on object's member function. however, have noticed object destroyed before thread starting. don't understand why.
my code:
#include <iostream> #include <thread> class myclass { public: myclass(){ std::cout << "myclass constructor called" << std::endl; } ~myclass(){ std::cout << "myclass destructor called" << std::endl; } void start(){ std::cout << "myclass starting" << std::endl; } }; int main() { myclass mine; std::thread t(&myclass::start, mine); t.join(); }
output:
myclass constructor called myclass destructor called myclass starting myclass destructor called myclass destructor called
desired output:
myclass constructor called myclass starting myclass destructor called
pass mine
reference: std::thread t(&myclass::start, std::ref(mine));
type of mine
myclass
, meaning pass value. std::thread
passes copy of newly created thread.
you need explicitly tell template passing mine
reference.
Comments
Post a Comment