why 2 times destructor called in this code?

Viewed 90

sorry but I cant understand why 2 times destructor called?

#include <iostream>
#include <thread>

class myClass
{
public:
    int integer;
    void operator()()
    {
        std::cout << "class: " << integer << "\t" << std::this_thread::get_id() << std::endl;
    }
    myClass(int h)
        : integer{h}
    {
    }
    ~myClass()
    {
        std::cout << "MyClass by int: " << integer << " destroyed!" << std::endl;
    }
};

bool myFunc(int x)
{
    myClass tempClass(x);
    std::thread one(tempClass);
    one.join();
    if (x <= 0)
        return 0;
    else
        return myFunc(x - 1);
}
int main()
{
    myFunc(10);
    return 0;
}

note : I'm just trying in MultiThreads. (training) and one more problem is that why before joining thread , my class has destroyed!

1 Answers

In the line

std::thread one(tempClass);

a copy of tempClass is created. Later on, both instances of myClass are destroyed.

You can pass tempClass by reference by using std::ref, but then you have to guarantee that tempClass remains valid (e.g. does not go out of scope, is brought in an invalid state by the main thread) throughout the life time of your thread (one).

You can also move tempClass into the other thread. You would still end up with two destructor calls and it would hardly make any difference in your case, but if myClass is difficult to copy, it can make a difference. In that case, you may want to read up on move semantics.

Related