简体   繁体   中英

c++ static variable initialization problem - referencing on another static const

I tried to declare two static variables in two different .cpp, one is trying to use another during initialization (eg Class B -> Class A). Code could be compiled if I have main.cpp which includes ah and bh 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: ah

#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(){};

bh

#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...

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM