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{//

Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several