next up previous
Next: Redefining of the static Up: C++/C Previous: String const

Static object initialization order

C++ doesn't guarantee the order the initilization of the static objects (or global object) at different translation units; But for those objects in the same translation units, their initialization order is guaranteed. That means if your program depends on the order the initilization, your program is not stable and portable. For example, the below code
InitLab.hpp
--------------------------------

class InitLab 
{
private:
    int i;
    static int count;
    
public:
    InitLab();

    void runit();

    
};

namespace 
{
    InitLab lab;
}
-----------------------------------
InitLab.cpp
-----------------------------------
#include "InitLab.hpp"
#include <iostream>

using namespace std;

int InitLab::count = 0;


InitLab::InitLab() 
{
    bool b = false;
    
    if (count++ == 0) {
        cout << "hello world" << endl;
        b  = (typeid(*cerr.rdbuf()) == typeid(InitLab));
        cout << b;
        
    }
    
    
}
If we compile the code by gcc 3.4.6, the program will get segment fault error; But if we use CC or other version of gcc, the program runs well. The problem is InitLab::InitLab will use cerr, which is another static object defined in iostream. The reason is C++ doesn't guarantee the cerr will be initlized when InitLab invokes it.

The solution is so called Swatchz counter. We put the

namespace {InitLab lab;}
in the header file. So any cpp file, once it includes the header file, an internal InitLab will be created and initlized. A counter is used to make sure only the first time when InitLab is created, it will be initlized; If InitLab::InitLab is using other static object (e.g., iostrea::cerr), we should include the iostream header file at the very begining of the InitLab header file, so that we ensure cerr is initilized prior to the InitLab (Note. cerr also takes the Swatchz counter pattern).

That means eventaully we have

namespace{Ostream cerr;}
namespace{InitLab lab;}
...


next up previous
Next: Redefining of the static Up: C++/C Previous: String const
Wei Lu 2007-11-06