Static initialization order

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tavianator
    New Member
    • Dec 2006
    • 38

    Static initialization order

    I realise that the order of initialization of global static objects across multiple translation units is undefined; however, if a function is defined in the same translation unit as a global static, is the global guaranteed to have been initialized by the time the function is called? For example: is the following code safe?

    foo.hpp:
    [code=cpp]
    struct foo { /* ... */ };

    extern foo f;
    extern foo b;

    foo& bar();
    [/code]

    foo.cpp:
    [code=cpp]
    #include "foo.hpp"

    foo f = bar();
    [/code]

    bar.cpp:
    [code=cpp]
    #include "foo.hpp"

    foo b;

    foo& bar() { return b; }
    [/code]
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Yes.

    And read this article: http://www.thescripts.com/forum/thread737451.html.

    Comment

    • tavianator
      New Member
      • Dec 2006
      • 38

      #3
      Really? I checked using g++, and it gave me different results depending on the compilation order of foo.cpp and bar.cpp. I managed to solve my problem a better way, though.

      Comment

      Working...