samedi 20 juillet 2019

Object destructor kept being called when multithreading, yet the object is not out of scope

I am not sure why even I called the object's member function, even it is still in it's scope, the destructor is still called. A simple example is shown as below:

#include<thread>
#include<iostream>
class Obj1
{
private:

public:
    ~Obj1();
    void testFunc();
};

Obj1::~Obj1()
{
    std::cout<<"destory\n";
}
void Obj1::testFunc(){
    std::cout<<"testfun\n";
}

#include "Obj1.hpp"
#include <thread>
#include <chrono>
int main()
{
    using namespace std::chrono_literals;
    Obj1 obj1 = Obj1();
    for(int i=0;i<100;i++){
        std::thread th =  std::thread(&Obj1::testFunc,obj1);
        std::this_thread::sleep_for(1s);
        std::cout<<"we wait\n";
    }
}

When I tried to run it, I can see the output:

destory
testfun
destory
we wait
terminate called without an active exception
Aborted (core dumped)

I wonder why obj1 is destroyed every time the thread ends?

Aucun commentaire:

Enregistrer un commentaire