views:

108

answers:

3

Let's say I have 2 singletons, allocated on the heap, for which no delete is ever called. Let's call them A and B. Is there any way to make sure B will be the first one to be destroyed?

I'm assuming the platform may matter on this one: Visual Studio 2005 Professional, Visual C++. Everything was built with cl.

+5  A: 

If they are heap allocated to normal pointers, and if delete is never called on those pointers, then they will never be destroyed, so the order of destruction is moot.

On the other hand, If you allocate them to static smart pointers, and if they are in the same translation unit, then the first one created will be the last one destroyed:

static std::auto_ptr <AType> a( new AType );  // destroyed second
static std::auto_ptr <BType> b( new BType );  // destroyed first

And lets have no nitpicking about static being deprecated :-)

anon
Nipticking. Excellent word. Never heard. (I'm not a native English speaker) Thanks, but I cannot give one more point. Sorry.
Notinlist
+4  A: 

You could register deleting of your singletons in atexit which is LIFO.

Alexander Poluektov
According to the link it's LIFO, I believe.
Asaf R
Thanks, just mixed up.
Alexander Poluektov
Doesn't matter whether it's LIFO or FIFO. You could register _one_ `atexit` function that deletes singletons in whatever order you want.
Graeme Perrow
@Graeme: That's only case if there exists function that knows about all your singletons.
Alexander Poluektov
@Alexander - Good point. +1 on the answer and the comment.
Graeme Perrow
+1  A: 

Short Answer: Yes

Long Answer:
Read this: http://stackoverflow.com/questions/335369/finding-c-static-initialization-order-problems/335746#335746

Summary:

Basically if you use the classic pattern of static function variable to create your singeltons (So you get lazy evaluation and guaranteed destruction) then the order of destruction is the inverse of the order of creation.

To ensure that B is destroyed before A then B must be created before A. To do this just make the constructor of A get an instance of B.

See here: http://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289 for lots of links about singeltons.

Martin York