Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: C++
Expertise: All
Aug 20, 1999



Application Security Testing: An Integral Part of DevOps

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;

  //In file A.h:
#include "B.h"
class A
  static B b;

//In file A.cpp:
 B A::b; //definition of the static object member

    b.B_DoSomething();  // runtime crash: b hasn't been initialized

//In file B.h
 class B

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.h
class A
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date