Composite object destruction order

SOLVED

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

26
Rhomboid•

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.

1
SpiderboydkOP•

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.

1
Rhomboid•

Make another Inner that initializes the library, rather than trying to do it in Outer. The order of initialization of members is guaranteed (the order in which they are declared in the class.)

3
SpiderboydkOP•

Of course! This is exactly the simple, elegant and obvious solution I couldn't think of. Thank you.

1
nuggins•

Consider a class 'NewOuter' like your class 'Outer' above, except that it contains a reference to an instantiation of Inner. Then, if this Inner object were destructed first, the NewOuter object would contain an invalid reference. That leads me to believe that what you're looking for is impossible.

1
SpiderboydkOP•

Yeah, I may be thinking of this the wrong way.

You can read my response to Rhomboid for more context of what I'm trying to do.

1