devxlogo

Properly Initialize Static Objects in Different Files

Properly Initialize Static Objects in Different Files

The C++ standard does not guarantee any construction order among static objects defined in different translation units. To demonstrate the effect of this restriction, consider this small application: In a file called main.cpp file, an object of class A is instantiated. A has a static member object b, which is of type B. Inside the constructor of class A, a member function of the static object b is called:

   //in file main.cpp:#include "A.h"A a;main(){  a.A_DoSomething();}  //In file A.h:#include "B.h"class A{public:  A();  static B b;  A_DoSomething();};//In file A.cpp: B A::b; //definition of the static object member A::A() {    b.B_DoSomething();  // runtime crash: b hasn't been initialized }//In file B.h class B { public:   B();   B_DoSomething(); };

When A’s constructor invokes b.B_DoSomething(), the application crashes because the static object member b hasn’t been constructed yet (note that had b been declared as a nonstatic object, it would have been properly constructed at this time). Programmers often blame the compiler and submit bug reports to the vendor when they encounter this phenomenon. However, this is not a bug because the static object is not required to be initialized at that moment.

The solution is relatively simple: instead of using a static object directly, you should use a static member function that returns a reference to a local static object, as in this example:

 //in file A.hclass A{//

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist