Destruction order (e.g. singletons)

S

Stephan Keil

Hi all,

consider a class

class X {
static X& OneX() { static X sgl1; return sgl1; }
static X& TheX() { static X sgl2(OneX()); return sgl2; }
};

and two source files with global variables

// a.cpp
X a1;
X a2(X::TheX());

// b.cpp
X b1;
X b2(X::TheX());

As I understand it, two valid construction orders are
"a1 sgl2 sgl1 a2 b1 b2" and "b1 sgl2 sgl1 b2 a1 a2".

Now, two questions:
1. Is "a1 b1 sgl2 sgl1 b2 a2" also a valid construction order
(i.e. is it guaranteed that the global objects of a
translation unit are all constructed before any global object
of another translation unit)?
2. I would find it natural if the destruction order follows
always the reverse construction order.
But what does the standard say about the destruction order
(esp. for sgl1 and sgl2)? (And do current compiler follow
the standard in that point;-?)

Thanks, Stephan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top