jeudi 24 septembre 2015

How to not call mother's destructor from constructor on exception?

I have some classes Daughter1 and Daughter2 inherited from Mother:

class   Mother
{
public:
    Mother(); // Empty constructor.
    virtual ~Mother(); // Delete common daughter's stuff.

protected:
    // Common stuff of each daughter.
};

The common stuff of every daughter class has the same deletion method, so the mother is in charge. However, their initialization is not the same, so they are in respective daughter's constructors:

class   Daughter1 : public Mother
{
public:
    Daughter1(); // Initialize mother's stuff
    ~Daughter1();
};

class   Daughter2 : public Mother
{
public:
    Daughter2(); // Initialize mother's stuff in a different way than Daughter1
    ~Daughter2();
};

The problem is: sometimes, a daughter constructor can fail to load its stuff and throws an exception. And when I declare a Daughter like this:

Daughter1   daughter();

And the constructor throws an exception, it calls the mother's destructor, which try to delete its stuff without an initialization, that lead inevitably to a segmentation fault.

What is the best way to avoid this kind of trouble?


Most of my stuff is composed of pointers, so I know I could simply initialize them to nullptr in the mother constructor and check them before trying a deletion in the destructor, but it only works with pointer and I'm looking for a global solution.

Aucun commentaire:

Enregistrer un commentaire