c++ - 在 C++ 中, "static initialization fiasco"是否仅影响引用另一个模块中定义的对象的数据成员?

标签 c++

以下示例是否合法且安全的 C++,或者是否有可能根据链接器决定调用全局对象的构造函数的顺序而崩溃?

a.hpp:

class A {
public:
  A(int val_);
  int val;
};

extern A a;

a.cpp:

#include "a.hpp"

A::A(int val_) : val(val_) {}

A a(1234);

b.cpp:

#include <cassert>
#include "a.hpp"

class B {
public:
  B(A &a);
  int &ref;
};

B::B(A &a) : ref(a.val) {}

B b(a);

int main(int argc, char **argv) {
  assert(b.ref == 1234);
  assert(&b.ref == &a.val);
}

我需要在我正在编写的一些真实代码中做这样的事情(显然我的 A 和 B 类比这个最小的例子复杂得多,但它们需要共享的数据成员是普通的旧整数和 bool 值)和我更愿意使用引用而不是指针。

最佳答案

是的,这可能会爆炸(无论如何根据标准),因为 b 的构造函数可以在 a 之前运行,然后 ([class. cdtor]/p1)...

For an object with a non-trivial constructor, referring to any non-static member or base class of the object before the constructor begins execution results in undefined behavior.

关于c++ - 在 C++ 中, "static initialization fiasco"是否仅影响引用另一个模块中定义的对象的数据成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30020090/

相关文章:

C++11 将传统指针转换为智能指针。使用来自 llvm 的最新 SVN Clang 和 libc++

c++ - Qt : pass values from a window to another

c++ - TSP 的 3-opt 优化代码

c++ - 如何从另一个派生类访问派生类的成员?

c++ - CLion对C++概念的支持

c++ - 指针数组成员,是否初始化?

c++ - 如何在 OpenGL 中进行 2D 缩放(GLFW,很高兴)?

c++ - 如何关闭先前打开的 shell (C++)

c++ - 转换指针引用的字符串

c++ - 在 C++ 中查找带零的整数的长度?