Consider three classes like this:
class A {
int bar;
};
class B {
A* a;
public:
B(*A na)
: a(na)
{}
~B() {
a->bar = 0;
}
};
class Foo {
A* a;
B b;
public:
Foo()
: a(new A)
, b(a)
{}
~Foo() {
delete a;
}
};
Creating an instance of Foo, results in a Foo with a pointer to an A and a B with the same pointer.
When the instance of Foo is deleted, The pointer a is deleted and then the destructor of b is called, but ~B tries to access a, which was freed in ~Foo, which results in a segmentation fault.
Is there a way to call the destructor of b before running the body of ~Foo?
I know I could solve this, by making either b a pointer or making a a non-pointer. The latter doesn't work if A is abstract and I would like to know if it's possible without making b a pointer.
PS: A and B are both from a library, so I can't change their implementation.
Follow RAII principles.
Change Foo::a to std::unique_ptr<A>. Remove the delete from ~Foo.
It will now be destroyed after the end of ~Foo and after b.~Bar().
Note that members are created in the order of declaration, and destroyed in the opposite order. (The order in initialization lists does not change order of creation, surprisingly). So if you want a to outlive b, simply declare it first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With