The following code works fine when using e.g. int instead of std::string, std::map etc.
I have a global variable that needs an entry of the static member when using the default constructor, but this string is empty here. The variable "test" does not have to be inside the class itself. I think there is some initialization order problem involved with STL components (or non-primitives). Using C++14.
// MyClass.h
#include <string>
class MyClass{
public:
static const std::string test;
MyClass();
};
// MyClass.cpp
#include <iostream>
#include "MyClass.h"
const std::string MyClass::test = "Yooooooo";
MyClass::MyClass(){
std::cout << test << std::endl;
}
// main.cpp
#include <iostream>
#include "MyClass.h"
const MyClass c;
int main(){
//MyClass c; // Would work
std::cout << "There should be something above this line." << std::endl;
}
The order in which objects with the static storage duration are initialized in different compilation units relative to each other is unsequenced.
From the C++ 14 Standard (3.6.2 Initialization of non-local variables)
- ...Otherwise, the initialization of a variable is indeterminately sequenced with respect to the initialization of a variable defined in a different translation unit.
You have two variables with static storage duration in different compilation units
const std::string MyClass::test = "Yooooooo";
and
const MyClass c;
You could avoid the problem by declaring the variable with the inline specifier.
class MyClass {
public:
inline static const std::string test = "Yooooooo";
MyClass();
};