I'm trying to understand when the static initialization order fiasco is a real problem. If I use a string constant like kName
below would it suffer any of the problems of the static initialization order fiasco? Is this a problem in this case because an instance of Derived
can be created before kName
is initialized as in main.cpp
?
// Base.cpp
namespace test {
class Base {
public:
virtual ~Base() = default;
protected:
explicit Base(const std::string &name);
};
} // namespace test
// Derived.cpp
namespace test {
static const std::string kName = "my name";
class Derived : public Base {
public:
Derived() : Base(kName) {}
~Derived() override = default;
};
} // namespace test
// main.cpp
int main() {
test::Derived instance{};
return 0;
}
The main
function will not be called until all "global" variables are initialized. That includes static
member variables as well as variables in namespace
scope (static
or not).
So in this case it's no problem since you define the instance
inside the main
function.
It would be different if the definition of instance
was done statically outside the main
function.