What is the best way to initialize a private, static data member in C++? I tried this in my header file, but it gives me weird linker errors:
class foo
{
If you want to initialize some compound type (f.e. string) you can do something like that:
class SomeClass {
static std::list _list;
public:
static const std::list& getList() {
struct Initializer {
Initializer() {
// Here you may want to put mutex
_list.push_back("FIRST");
_list.push_back("SECOND");
....
}
}
static Initializer ListInitializationGuard;
return _list;
}
};
As the ListInitializationGuard
is a static variable inside SomeClass::getList()
method it will be constructed only once, which means that constructor is called once. This will initialize _list
variable to value you need. Any subsequent call to getList
will simply return already initialized _list
object.
Of course you have to access _list
object always by calling getList()
method.