Destruction order (e.g. singletons)

Discussion in 'C++' started by Stephan Keil, Nov 16, 2004.

  1. Stephan Keil

    Stephan Keil Guest

    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
    Stephan Keil, Nov 16, 2004
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Davlet Panech
    Replies:
    4
    Views:
    335
    Davlet Panech
    Nov 10, 2006
  2. Dennis Jones
    Replies:
    2
    Views:
    310
    Dennis Jones
    Jan 5, 2007
  3. BeautifulMind
    Replies:
    7
    Views:
    640
    Ron Natalie
    Feb 8, 2007
  4. Lilith

    Order of destruction

    Lilith, Apr 3, 2008, in forum: C++
    Replies:
    3
    Views:
    466
    James Kanze
    Apr 4, 2008
  5. Victor Bazarov
    Replies:
    11
    Views:
    734
    James Kanze
    Dec 9, 2009
Loading...

Share This Page