So I have this class kind of class:
class Base
{
public:
Base() { task_ = std::thread(&DexHandlerBase::running_task, this); }
virtual ~Base(){ /*send signal to task_ to stop then */ task_.join();}
protected:
virtual int some_check(int) = 0;
private:
void running_task() { some_check(123); }
std::thread task_;
}
class Derived
{
protected:
int some_check(int) override; //here I use my_data
private:
std::string my_data = "test";
}
An exception spawn up sometimes when the program close.
My guess is that the default Destructor of derived is called, Derived default destructor run and then my_data
get destructed. Then the Base class destructor is called and it signal the thread that its going to be destroyed and wait. But the thread is running a task that is a call to a virtual function , this function use my_data that no longer exist.
So there is a dependency from the Base class to the Derived class data. I dont want to move data up, and the function has to be virtual. Shall I override the destructor in each derived class so it closes the thread or is there a better design for this ?
CodePudding user response:
I had similar problems when trying to run async operations in Base classes. Most likely after the destructor of Derived
is called, the task_
tries to call virtual int some_check(int) = 0;
which is pure virtual, so it is illegal, because Derived
doesn't exist anymore. You should make sure that your Derrived::~Derived()
stops the asyc operation by /*send signal to task_ to stop then */
. E.g. implement protected
Base::stopTask()
and call it in Derived
DTor.