【问题标题】:c++ static variable initialization problem - referencing on another static constc++静态变量初始化问题——引用另一个静态常量
【发布时间】:2019-03-04 05:10:42
【问题描述】:

我试图在两个不同的 .cpp 中声明两个静态变量,一个在初始化期间尝试使用另一个(例如 B 类 -> A 类)。如果我有包含 a.h 和 b.h 的 main.cpp,则可以编译代码。它在运行时崩溃(分段错误(核心转储))。我知道这是静态变量初始化的问题,静态变量 A 可能在静态对象 B 的初始化过程中尚未初始化。

请问通过改变我的编码方式或任何设计模式来解决此类问题的正确方法是什么?

我看到一些帖子说在编译期间使用“constexpr”来强制 A::a 初始化,我陷入了语法错误。

static constexpr std::string a;     // in a.h
constexpr std::string A::a="AAA";   // in a.cpp

错误:

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";

完整代码如下: 呵呵

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

我曾想过创建一个全局 getter 函数

getA()
{
   static std::string A::a;  //hope that would force A::a initialization
   return A::a;
}

然后

static B b(getA())

看起来很丑……

【问题讨论】:

  • 你应该避免using namespace std;,尤其是在标题中。 (无论如何你都正确地写了std::)。

标签: c++ linux g++ rhel


【解决方案1】:

困扰你的问题被称为静态初始化顺序问题。它被认为是一个“经典”问题。绕过它的想法是“手动管理”变量的初始化顺序。

这是关于它的经典常见问题解答条目:https://isocpp.org/wiki/faq/ctors#static-init-order-on-first-use

【讨论】:

  • 是的,这就是我最后所说的。考虑到我可能有许多静态 const 字符串变量,在这种情况下我不想为每个变量都设置一个函数。想知道较新的 c++ 版本是否具有有助于避免这种情况的功能。我试过 constexpr,你认为在编译时强制初始化会有所帮助吗?我以为它会,但它似乎不起作用。
猜你喜欢
  • 2018-03-15
  • 1970-01-01
  • 2012-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-13
  • 2011-08-22
  • 2010-12-22
相关资源
最近更新 更多