What is a static initialization problem?

Article ID: 1259
Last updated: 07 Jun, 2012
Article ID: 1259
Last updated: 07 Jun, 2012
Revision: 1
Views: 5916
Posted: 01 Jan, 2000
by --
Updated: 07 Jun, 2012
by Rehme L.

Problem


 What is a static initialization problem and how does it affect an application?




Cause


A static initialization problem arises if there are two objects in two different translation units (object modules) where one is dependent on the other as shown below.

Typical static initialisation problem:

// foo.cpp

std::string s ("foo");

// bar.cpp

extern std::string s;

struct A
{
    A () {
        a_ = s;
    }
    std::string a_;
};

A a;

As the order of initialization of objects 'a' and 's' is not defined by the compiler, this dependency may cause problems trying to access objects before they are initialized.




Action


One can fix the problem by moving all the global objects into one translation unit or by creating a factory method that returns objects created. So, for instance, fix the dependency by creating a factory function that creates a string object:

// foo.cpp

std::string& get_s()
{
 static std::string s ("foo");
 return s;
}

// bar.cpp

extern std::string s;

struct A
{
    A () {
        a_ = get_s();
    }
    std::string a_;
};

A a;

Hence, look at where all the global objects in an application are declared, and, if possible move them into one translation unit or implement a fix as shown here.


This article was:   Helpful | Not helpful
Report an issue
Article ID: 1259
Last updated: 07 Jun, 2012
Revision: 1
Views: 5916
Posted: 01 Jan, 2000 by --
Updated: 07 Jun, 2012 by Rehme L.

Others in this category