Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

global static const string won't get initialized

Tags:

c++

Running c++ on Ubuntu.

in configuration.h file i have this (global):

static const string APP_CONFIG_FILE_NAME = "cfg";

in my configuration.cpp (which is singleton by the way, so load configuration is called by constructor of Configuration) i do this:

void Configuration::loadConfiguration() {
    cout<< "config file name "  << APP_CONFIG_FILE_NAME.data();
        load();
}

The load configuration will be called from another global: (this is the key point for the failure)

Timer t(Configuration::Instance()->timeout);

i see that the cost string is not initialized (empty). If i replace the string with char* its initialized in my expected order.

However on another program the same classes for configuration work, so i dont know the problem.

There is another question but not the same since there its not a global.

like image 892
Avihai Marchiano Avatar asked Oct 14 '25 04:10

Avihai Marchiano


1 Answers

It gets initialized, of course. However, it is likely being initialized in the order you don't want/expect it initialized in.

Specifically, it is probably not constructed by the time you use it because you use it during construction of another global.

Unfortunately, you don't have a good way to portably specify initialization order of global data. Initialization order among multiple files is not defined by the standard, although it is likely specified by your toolchain. Consequently, altering the order of compilation or building using another toolchain can result in a different initialization order. Search for "static initialization order fiasco" for more details.

One way to avoid this issue is to declare your static data in a function:

const std::string& AppConfigFileName() {
  static const std::string name("cfg");
  return name;
}

Although...I don't see why this must be static (the function above allows you to return by value -- no need for static). Plus, I don't see why this could not be a plain C string, since you just treat it as a C string in your config loader.

like image 110
justin Avatar answered Oct 16 '25 19:10

justin