Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

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

 

 

 

 

 


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

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date