Composite object destruction order
Hi everybody. I have trouble with the destruction order of composite objects. Look at this example:
#include <iostream>
using namespace std;
class Inner {
public:
Inner() {cout << "Inner" << endl; };
~Inner() {cout << "~Inner" << endl; };
};
class Outer {
public:
Inner inner;
Outer() {cout << "Outer" << endl; };
~Outer() {cout << "~Outer" << endl; };
};
int main() {
Outer outer;
return 0;
}
The composite object will destroy before the object it's composed of, i.e. it will produce:
Inner
Outer
~Outer
~Inner
I want Inner to be destroyed before Outer. How can I do this in an elegant way?
The construction order isn't important.
The usage of the Inner object is going to be speed sensitive, so I would prefer to avoid using heap allocation and dereferencing.
I don't know if it's just me, who's too dumb to see an obvious solution, but what would you suggest?
Posted Sep 18, 2014, 2:43 PM UTC
Well, I suppose you could create a discriminated union, giving you precise control of the lifetime of
Inner. But I think the real question is why? Why do you want to do this? There's probably a better way.Just my thoughts - I think I'm heading for a code smell here, which is why I asked for your input. :-)
I'm making classes to use RAII to manage resources attained from a C library. "Outer" initializes/cleans up the library and a few "Inners" allocate/free a few unique resources.
Maybe I should shove everything into a single class, but that would contest the single responsibility principle.
Make another
Innerthat initializes the library, rather than trying to do it inOuter. The order of initialization of members is guaranteed (the order in which they are declared in the class.)Of course! This is exactly the simple, elegant and obvious solution I couldn't think of. Thank you.