Home > Blogs > 30 C++ Tips in 30 Days: Tip # 25 overcoming static initialization dependencies

30 C++ Tips in 30 Days: Tip # 25 overcoming static initialization dependencies

By  Dec 15, 2007

Topics: Programming, C/C++

The static initialization problem bites novices and experienced programmers alike. The problem occurs when a translation file attempts to access an object with static storage type that is declared in a separate translation unit. At present, C++ offers no solution to this problem but there is a workaround.

Here's a common scenario: source file first.cpp define a static data member of a class and provided an initializer for it. Source file second.cpp #includes first.h and attempts to examine the value of the static data member. When you execute that statement, the program crashes.

//----first.h
class C
{
public:
   static const int i;
};

//----first.cpp
#include "first.h"
const int C::i=5; 

//----second.cpp
#include "first.h"
int MIN=C::i; //crash here 

This is because the order of initialization of static members is specified only within the bounds of their translation unit. If another translation accesses an object with static storage, there's no guarantee that that object has been initialized already.

To avert this problem, avoid direct access to objects with static storage duration. Instead, replace each object with a static function that declares the object as a local static object:

//----first.h
class C
{
public:
   static int get_i();
};
 

//----first.cpp
int C::get_i()  
{
  static int i=5;
  return i;
}

//----second.cpp
#include "first.h"
int MIN=C::get_i(); //now safe
 

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.

Other Things You Might Like

Xamarin Unleashed

Xamarin Unleashed