narengi February 2016

Undesirable destructor call when starting a thread on a member function

I have an event loop in my main function, in which I would like to create an object and run a thread on the object's member function. However, I have noticed that the object is destroyed before the thread is even starting. I don't understand why.

My code:

#include <iostream>
#include <thread>

class MyClass {
public:
    MyClass(){
        std::cout << "MyClass constructor is called" << std::endl;
    }
    ~MyClass(){
        std::cout << "MyClass destructor is called" << std::endl;
    }    
    void start(){
        std::cout << "MyClass is starting" << std::endl;
    }
};

int main()
{
        MyClass mine;
        std::thread t(&MyClass::start, mine);
        t.join();
}

Output:

MyClass constructor is called
MyClass destructor is called
MyClass is starting
MyClass destructor is called
MyClass destructor is called

Desired output:

MyClass constructor is called
MyClass is starting
MyClass destructor is called

Answers


David Haim February 2016

pass mine by reference: std::thread t(&MyClass::start, std::ref(mine)); the type of mine is MyClass, meaning you pass it by value. so std::thread passes a copy of it to the newly created thread.

you need to explicitly tell the template you are passing mine by reference.


rajenpandit February 2016

std::thread internally creates local object and call copy constructor multiple times and destroy local object once used. Because of that you are getting more than one output as MyClass destructor is called. if you want to check the behavior of object construction then you can include a copy constructor in your class.

Post Status

Asked in February 2016
Viewed 1,459 times
Voted 7
Answered 2 times

Search




Leave an answer