问题描述
来自我用c ++实现了一个类似于所选解决方案的系统
现在我的问题是,用户Daniel James在那里说这个解决方案可能不适用于每个编译器(我目前使用gcc),并且没有在c ++标准中定义。
假设我有一个接口的抽象基类和一个工厂类作为单例存储指向函数的指针,然后我有一个类似于这样的助手类:
i> base.hpp
...
class implRegistrator {
public:
implRegistrator(constructPointer){
factory :: registerImpl(constructPointer);
};
}
一个实现(通过宏)创建这个类的一个对象,注册本身:
impl1.cpp
...
implRegistrator * impl1 = new implRegistrator(getConstructPointer());
这个解决方案与C ++标准的兼容程度如何?是否安全地假设类实例化impl1.cpp甚至会发生,因为主程序中的任何内容都不会在编译时显式调用它?
谢谢提前给出任何答案。
所以,在Angew指出过我的位置后,脚注 34
在 [basic.start.init]§4
中声明:
具有初始化副作用的静态存储持续时间的非局部变量即使未使用odr也必须初始化(3.2,3.7.1)。
这实际上解决了这里提到的问题。自注册类没有被使用,并且修改了工厂对象的状态,因此初始化时带有副作用。
因此,根据这个脚注,它实际上是安全的做一个自我注册,就像我和Skizz提到的一样。
编辑:正如马特麦克纳布所说,我不应该依赖脚注。所以这里是脚注引用的规范的一部分:[Basic.stc.static]§2
如果一个静态存储的变量持续时间有初始化或具有副作用的析构函数,即使它看起来没有被使用,它也不会被消除,除非类对象或它的复制/移动可以按照12.8的规定被消除。
Coming from this thread I implemented a similar system in c++ to the chosen solution there.
My problem now is that it is stated there by the user Daniel James that this solution might not work with every compiler (I'm using gcc currently) and is not defined in the c++ standard.
Suppose I have an abstract base-class for the interface and a factory-class as a singleton that stores pointers to a function that constructs the specific classes derived from that interface.
then I have a helper class that looks roughly like this:
base.hpp
...
class implRegistrator {
public:
implRegistrator(constructPointer) {
factory::registerImpl(constructPointer);
};
}
And an implementation that (through a macro) creates an object of this class to register itself:
impl1.cpp
...
implRegistrator* impl1 = new implRegistrator(getConstructPointer());
How compatible to the C++ standard is this solution? Is it safe to assume that the class instantiation ind impl1.cpp will even happen, since nothing from the main program will actually explicitly call it at compile-time?
Thanks in advance for any answers.
So after looking a bit further into the standard at the position where Angew pointed me before, I noticed footnote 34
in [basic.start.init]§4
of the standard that states:
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).
And that actually addresses the problem which is mentioned here. The self registering class is not odr-used and modifies the state of the factory object, thus having an initialization with side-effects.
So per this footnote it is actually safe to do a self registration like the one mentioned by me and Skizz.
Edit: As Matt McNabb mentioned, I shouldn't have relied on the footnote. So here is the part of the specification that the footnote refers to: [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.
这篇关于C ++自注册类有多安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!