global variables - Static initialization order issue in C++ -


this variation of old theme: initialization order of static objects in different translation units not defined.

below stripped-down example of particular scenario. classes g , f non-pod types. f depends on g sense construct instance of f need number of instances of g. (for example, f message application emits, , instances of g components of such messages.)

g.hpp

#ifndef g_hpp #define g_hpp  struct g {     g() {} // ... };  inline g operator+(g, g) { return g(); }  #endif 

gs.hpp

#ifndef gs_hpp #define gs_hpp  #include "g.hpp"  extern const g g1; extern const g g2; extern const g g3; extern const g g4; extern const g g5; extern const g g6; extern const g g7; extern const g g8; extern const g g9;  #endif 

gs.cpp

#include "gs.hpp"  const g g1; const g g2; const g g3; const g g4; const g g5; const g g6; const g g7; const g g8; const g g9; 

f.hpp

#ifndef f_hpp #define f_hpp  #include "g.hpp"  struct f {     f(g) {} // ... };  #endif 

fs.hpp

#ifndef fs_hpp #define fs_hpp  #include "f.hpp"  extern const f f1; extern const f f2; extern const f f3;  #endif 

fs.cpp

#include "fs.hpp" #include "gs.hpp"  const f f1(g1 + g2 + g3); const f f2(g4 + g5 + g6); const f f3(g7 + g8 + g9); 

f's constructor takes argument result of applying operator+ instances of g. since instances of both f , g global variables, there not guarantee instances of g have been initialized when constructor of f needs them.

the particularity here there many gs , fs on place, , keep syntax as possibly close code posted above, while still enforcing construction of g whenever f needs it.

from http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.15 .

change global objects functions construct object on first use.

// gs.hpp const g & g1();  // gs.cpp const g & g1() {   static const g* g1_ptr = new g();   return *g1_ptr; }  // fs.cpp const f & f1() {   static const f* f1_ptr = new f(g1() + g2() + g3());   return *f1_ptr; } 

or if can't stand adding ()s, use #defines hide them:

// gs.hpp const g & get_g1(); #define g1 (get_g1()) // definition of get_g1() g1() prev. example 

Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -