I want to initialize some lookup table in a shared library, I want to see if this is a valid way, and if it is continue using it in more libraries I am about to write.
typedef std::map<std::string, int> NAME_LUT;
NAME_LUT g_mLUT;
namespace
{
bool OneTimeInit()
{
::g_mLUT.insert(NAME_LUT::value_type("open", 1));
::g_mLUT.insert(NAME_LUT::value_type("close", 2));
return true;
}
bool bInit = OneTimeInit(); // Just to make initialization happen
}
It seems to work fine on both Visual Studio, and gcc (Linux). Only gcc complains that bInit is not used anywhere.
- Is it possible that initialization is optimized out (
bInitnot used), or language does not allow it (because of the side effect). - It sure looks like a good cross platform way of handling onetime initialization, but I am not sure if this is the best approach.
- Does it make sense to make
OneTimeInitdeclared static? (i.e. usestatic bool OneTimeInit() {...}), or namespace alone is a better approach to make it unique to this compilation unit
I don’t quite like the idea of variables with static storage, but if you are going to do so, you can actually simplify the code by just writing a function that will initialize your object:
Note that this has all of the usual initialization order issues (accross different translation units, and specially with dynamic libraries)