Reputation: 3406
I'm having a problem with initialization order of a const static string class member. Some code:
constants.h
class Constants
{
public:
// not used right now
Constants& getInstance();
const static std::string CONST_STRING;
};
constants.cpp
const std::string Constants::CONST_STRING = "my string";
Constants& Constants::getInstance();
{
static Constants c;
return c;
}
which is classic const static initialization (ignoring the getInstance
). However, if I then try to use this constant elsewhere in another translation unit like this:
class OtherClass
{
public:
OtherClass()
{
// tried uncommenting next line
// Constants::getInstance();
std::string str( Constants::CONST_STRING );
std::cout << str;
}
}
OtherClass obj; // note global
the CONST_STRING
is empty, i.e. it has been constructed but not initialized. I know that global initialization order is not defined across translation units and I'm guessing something like that applies here?
However, removing the commented out line that attempts to ensure that Constants is fully constructed before it is used (I don't believe it is needed but giving it a go....) still doesn't fix things.
Questions:
constexpr
something that could be used here?Upvotes: 1
Views: 195
Reputation: 2843
Maybe this is what are you looking for:
const std::string & GetConstantsString(){
static const std::string CONST_STRING = "My string";
return CONST_STRING;
}
As @AndreyT pointed out, literal type const static only are allowed to have in-class initializers so my option #1 will not work
Upvotes: 1
Reputation: 308091
The initialization of globals within a translation unit is going to occur in hidden code within that translation unit. You can't control the order in which those bits of hidden code are going to be called.
Constants with basic data types can be initialized at compile time rather than run time, so this would work:
const char Constants::CONST_STRING[] = "my string";
Upvotes: 1