Rag*_*gas 5 c++ gcc class standards-compliance
来自这个线程我在c ++中实现了一个类似的系统到那里选择的解决方案.
我现在的问题是用户Daniel James在那里说这个解决方案可能不适用于每个编译器(我现在使用的是gcc)并且没有在c ++标准中定义.
假设我有一个接口的抽象基类和一个工厂类作为单例,它存储指向构造从该接口派生的特定类的函数的指针.
然后我有一个看起来大致如下的助手类:
base.hpp
...
class implRegistrator {
public:
implRegistrator(constructPointer) {
factory::registerImpl(constructPointer);
};
}
Run Code Online (Sandbox Code Playgroud)
并且(通过宏)创建此类的对象以注册自身的实现:
impl1.cpp
...
implRegistrator* impl1 = new implRegistrator(getConstructPointer());
Run Code Online (Sandbox Code Playgroud)
这个解决方案与C++标准的兼容性如何?是否可以安全地假设类实例化ind impl1.cpp甚至会发生,因为主程序中的任何内容都不会在编译时显式地调用它?
提前感谢您的任何答案.
在这里Angew前指着我的位置进一步看起来有点成标准后所以,我注意到脚注34中[basic.start.init]§4标准的各国:
A non-local variable with static storage duration having initialization with side-effects must be initialized even if it is not odr-used (3.2, 3.7.1).
这实际上解决了这里提到的问题。自注册类不是 odr 使用的,它会修改工厂对象的状态,因此具有带有副作用的初始化。
所以根据这个脚注,像我和 Skizz 提到的那样进行自我注册实际上是安全的。
编辑:正如马特麦克纳布所提到的,我不应该依赖脚注。所以这里是脚注所指的规范部分:[Basic.stc.static] §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, except that a class object or its copy/move may be eliminated as specified in 12.8.