vendredi 16 décembre 2022

How to solve a dependency between Base and Derived class data

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 ?

Aucun commentaire:

Enregistrer un commentaire