c++ - 使用静态数据的构造函数在 main() 之前执行工作

标签 c++ constructor static

我们的系统有一个基于插件的架构,每个模块实际上都有一个“主要”功能。在调用模块的 main() 之前,我需要运行一小段代码。我已经成功地将代码放入一个虚拟类的构造函数中,然后声明该类的一个静态变量,例如:

namespace {
class Dummy {
public:
    Dummy() { /* do work here */ }
};

   Dummy theDummy;
}

void main() {...}

这似乎工作得很好,但就保证代码运行的编译器而言,它是否是一个有效的解决方案?它是否有机会检测到 theDummy 没有在系统中的其他任何地方被引用并完全编译/链接它,或者它会意识到构造函数需要运行吗?谢谢

最佳答案

This seems to work well, but is it a valid solution in terms of the compiler guaranteeing the code will run? Is there any chance it could detect that theDummy is not referenced anywhere else in the system and compile/link it away completely, or will it realise that the constructor needs to run?

参见 n3797 S3.7.1/2:

If a variable with static storage duration has initialization or a destructor with side effects, it shall not be eliminated even if it appears to be unused,

是的,初始化必须运行。不能简单省略。

参见 S3.6.2/4:

It is implementation-defined whether the dynamic initialization of a non-local variable with static storage duration is done before the first statement of main. If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first odr-use (3.2) of any function or variable defined in the same translation unit as the variable to be initialized.

是的,必须在任何代码在同一翻译单元中运行之前完成初始化。

在您的插件中使用名为 main() 的入口点并不特别重要。

一切顺利。


根据评论,您确实需要确保您的 Dummy 构造函数和您的 main 函数在同一个翻译单元中才能正常工作。如果它们是单独编译的并且只链接在一起,则此保证将不适用。

关于c++ - 使用静态数据的构造函数在 main() 之前执行工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23519823/

相关文章:

c++ - OSX native API 视频解码 C++

c++ - 模板模板参数推导与 sfinae

qt - 静态编译 Qt 4.6.2

javascript - 为什么 "this"关键字不能与下面代码中的类中的静态方法一起使用?

c++ - 64位代码洞穴返回不正确的入口点位置

c++ - QListView selectionModel 不发送 selectionChanged 信号

c++ - QVector 与 'operator=' 不匹配

c++ - 具有模板化构造函数(其他类型)的模板化类

c++ - 为什么要使用 const 进行隐式转换?

java - 如何从空引用访问静态变量?