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
EDIT: I missed the
MyObjectpart 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
Bdoes not “own” the object passed by reference, therefore the objectsaandbhave different life cycles. If the object refered to byB::a_is destroyed,B‘s destructor will access an invalid reference.Some code to explain what I mean: