以下示例是否合法且安全的 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/