C++无状态类的静态初始化
假设我有一个类 T,其中
- T 没有虚函数。
- T 实例没有状态。
- T 具有其自身的静态成员实例。
- T本身没有其他状态。
C++ 静态初始化失败会毁掉我的程序吗?我不这么认为,因为即使其中一个静态实例在使用前未初始化,那也没关系,因为 T 对象是无状态的。
我有兴趣为类似枚举的类执行此操作,如下所示:
// Switch.h
class Switch {
public:
static Switch const ON;
static Switch const OFF;
bool operator== (Switch const &s) const;
bool operator!= (Switch const &s) const;
private:
Switch () {}
Switch (Switch const &); // no implementation
Switch & operator= (Switch const &); // no implementation
};
// Switch.cpp
Switch const Switch::ON;
Switch const Switch::OFF;
bool Switch::operator== (Switch const &s) const {
return this == &s;
}
bool Switch::operator!= (Switch const &s) const {
return this != &s;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了回答你的问题的第一部分,如果
T
有一个有副作用的构造函数,那么你实际上可能会被静态初始化惨败所烧毁。To answer the first part of your question, if
T
has a constructor which has side effects then you can in fact get burned by static initialization fiasco.我感兴趣的是,您从包装在名称空间或类中的枚举中看到的优点是什么:
在大多数情况下使用起来会更简单(在您的实现中,您要求用户使用引用或指针,如对象是不可复制的),它需要更少的代码(不需要禁用构造函数,并创建运算符)...
事实上,在即将推出的标准中,您几乎可以免费获得它,甚至不需要使用命名空间:
I am interested in what are the advantages that you see from, say, an enum wrapped in either a namespace or a class:
It will be simpler to use in most cases (in your implementation you require users to employ either references or pointers, as the objects are non-copyable), it requires less code (no need to disable the constructors, and create the operators)...
As a matter of fact, in the upcoming standard you almost get that for free without even the use of the namespace:
您真的打算使用指针值来比较“状态”吗?我同意@Drew,这是一个有趣的想法。不过,如果我们假设这是一个仅包含标头的实现,我不确定标准是否能保证它正常工作。
考虑一下当多个编译对象包含相同的
Switch::ON
和Switch::OFF
定义时会发生什么情况。由于这些是变量,而不是函数,因此链接器必须在它们之间任意做出决定。当您运行测试时,流行的编译器会说什么:gcc 3、gcc 4、microsoft C++ 2005、2008 和 2010,以及 Edison Design Groups 的编译器之一,例如 http://www.comeaucomputing.com/ ?
测试将包括:
和
所述
Do you really intend to use pointer values to compare "state"? I agree with @Drew, it's an interesting idea. I'm not sure it is guaranteed by the standard to work, though, if we assume that this is a header-only implementation.
Consider what happens when multiple compilation objects contain the same definition for
Switch::ON
andSwitch::OFF
. Since these are variables, and not functions, the linker would have to decide, arbitrarily, between them.When you ran a test, what did the popular compilers say: gcc 3, gcc 4, microsoft C++ 2005, 2008, and 2010, and one of the Edison Design Groups' compilers such as http://www.comeaucomputing.com/ ?
Said test would consist of:
and
and