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 (
bInit
not 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
OneTimeInit
declared static? (i.e. usestatic bool OneTimeInit() {...}
), or namespace alone is a better approach to make it unique to this compilation unit