Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructor order

Tags:

c++

I have a C++ class hierarchy that looks something like this:

class A;

class B
{
public:
    B( A& a ) : a_( a )
    {
    };

private:
    A& a_;
};

class MyObject
{
public:
    MyObject() : b_( a_ )
    {
    };

private:
    A a_;
    B b_;
};

Occasionally, it will happen that in B's destructor I will get invalid access exceptions relating to its reference of A. It appears that A is destroyed before B.

Is there something inherently wrong with using class members to initialize other members? Is there no guarantee of the order of destruction?

Thanks, PaulH

like image 966
PaulH Avatar asked Aug 03 '26 03:08

PaulH


1 Answers

EDIT: I missed the MyObject part of your question so my original answer will probably not be of much help. I guess your problem lies in the code you did not post, the stripped-down example should work fine.


Class B does not “own” the object passed by reference, therefore the objects a and b have different life cycles. If the object refered to by B::a_ is destroyed, B's destructor will access an invalid reference.

Some code to explain what I mean:

class A;

class B {
public:
    B(A a) : a_(a) {}  // a is copied to a_
    ~B() { /* Access a_ */ }
private:
    A a_;
};

class C {
public:
    C(A& a) : a_(a) {}  // a_ is a reference (implicit pointer)
                        // of an external object.
    ~C() { /* Access a_ */ }
private:
    A& a_;
};


int main(int argc, char** argv) {
    A* a = new A();

    B b(*a);
    C c(*a);

    delete a;
    // Now b has a valid copy of a, c has an invalid reference.
}
like image 149
Ferdinand Beyer Avatar answered Aug 05 '26 20:08

Ferdinand Beyer