c++ - 跨文件的依赖变量之间的初始化顺序是什么?

标签 c++

假设我有以下代码:

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/

相关文章:

c++ - 尝试编写一个 C++ 堆栈程序

c++ - macOS (OSX) 上的 ncurses 找不到 xterm-256color

c++ - Poco 可以与 LLVM 标准 C++ 库一起使用吗?

c# - Protocol Buffer ,让 C# 与 C++ 对话 : type issues and schema issues

c++ - 可视化源

c++ - 为什么一个代码会产生内存泄漏而另一个不会?

c++ - 为什么 VS 做 imul rax,rax,0 而不是简单的移动?

c++ - 求所有可能的点对之间力的总和?

c++ - Netbeans Cpp 编译并运行项目,但不使用 cppunit 进行测试

C++ operator< 重载结构