假设我有以下代码:
extern std::string first_string; //defined in another file
std::string another_string(first_string + "some other string");
我的问题是:
标准是否保证 first_string
总是在 another_string
之前初始化?
如果不是,那么在实践中应该避免这样的代码吗?
我试图通过阅读 C++ 标准 N3485 第 3.6 和 3.7 节来解决这个问题。但是我没有找到好的答案。如果您在起草答案时能指出标准的一部分,我将不胜感激。 感谢您的帮助。
最佳答案
顺序未定义。
C++ FAQ :
suppose you have two static objects x and y which exist in separate source files, say x.cpp and y.cpp. Suppose further that the initialization for the y object (typically the y object's constructor) calls some method on the x object.
That's it. It's that simple.
The tragedy is that you have a 50%-50% chance of dying. If the compilation unit for x.cpp happens to get initialized first, all is well. But if the compilation unit for y.cpp get initialized first, then y's initialization will get run before x's initialization, and you're toast. E.g., y's constructor could call a method on the x object, yet the x object hasn't yet been constructed.
并查看 How do I prevent the "static initialization order fiasco"? .
关于c++ - 跨文件的依赖变量之间的初始化顺序是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16782521/