Reputation: 79
I tried to declare two static variables in two different .cpp, one is trying to use another during initialization (e.g. Class B -> Class A). Code could be compiled if I have main.cpp which includes a.h and b.h. It crashed during run time (Segmentation fault (core dumped)). I understand it is a problem with static variable initialization, static variable A might yet to be initialized during the initialization of static object B.
May I ask what is the proper way to resolve this kind of problem by changing the way I code or any design pattern would help?
I have seen some post saying to use "constexpr" to force A::a initialization during compile time, I got sucked in syntax error.
static constexpr std::string a; // in a.h
constexpr std::string A::a="AAA"; // in a.cpp
errors:
a.h:7:34: error: constexpr static data member ‘a’ must have an initializer
static constexpr std::string a;
a.cpp:4:26: error: redeclaration ‘A::a’ differs in ‘constexpr’
constexpr std::string A::a="AAA";
FULL CODE are below: a.h
#include <string>
using namespace std;
class A
{
public:
static const std::string a;
A();
~A();
};
a.cpp
#include "a.h"
using namespace std;
const std::string A::a("AAA");
A::A(){};
A::~A(){};
b.h
#include <string>
using namespace std;
class B
{
public:
B(const std::string& a );
~B();
};
b.cpp
#include "b.h"
#include "a.h"
#include <iostream>
static const B b(A::a);
B::B(const std::string& s){ cout <<"B obj::" << s << endl; };
B::~B(){};
I have thought of creating a global getter function
getA()
{
static std::string A::a; //hope that would force A::a initialization
return A::a;
}
and then
static B b(getA())
it looks ugly...
Upvotes: 1
Views: 601
Reputation: 40060
What bites you has been dubbed static initialization order problem. It is considered a "classic" problem. The idea to circumvent it is to manage manually" the order in which variables are initialized.
Here is a classic FAQ entry about it: https://isocpp.org/wiki/faq/ctors#static-init-order-on-first-use.
Upvotes: 3