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.

trincot
  • 317,000
  • 35
  • 244
  • 286
Geo
  • 93,257
  • 117
  • 344
  • 520
  • Read this: http://stackoverflow.com/questions/335369/finding-c-static-initialization-order-problems/335746#335746 – Martin York Feb 04 '10 at 14:08
  • If the destruction order between them matters, isn't that a hint with a sledgehammer that you shouldn't make them singletons? – jalf Feb 04 '10 at 14:23

3 Answers3

5

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 :-)

  • Nipticking. Excellent word. Never heard. (I'm not a native English speaker) Thanks, but I cannot give one more point. Sorry. – Notinlist Feb 04 '10 at 14:06
4

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

Alexander Poluektov
  • 7,844
  • 1
  • 28
  • 32
1

Short Answer: Yes

Long Answer:
Read this: Finding C++ static initialization order problems

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: C++ Singleton design pattern for lots of links about singeltons.

Community
  • 1
  • 1
Martin York
  • 257,169
  • 86
  • 333
  • 562