在《The C++ Language》一书中,作者声称
Sometimes, when you design a library, it is necessary, or simply convenient, to invent a type with a constructor and a destructor with the sole purpose of initialization and cleanup. Such a type would be used once only: to allocate a static object so that the constructor and the destructor are called.
我对这个声明指的是哪种场景感兴趣?或者这个声明如何帮助软件设计?
书中还给出了例子
class Zlib_init{
Zlib_init( );
~Zlib_init( );
};
class Zlib{
static Zlib_init x;
}
书上说
Unfortunately, it is not guaranteed that such an object is initialized before its first use and destroyed after its last use in a program consisting of separately compiled units.
为什么会发生这种情况?
感谢您的澄清。
最佳答案
C++ 标准没有指定静态对象的创建顺序。因此,如果你需要静态对象中的一些层次结构,你需要它们相互依赖(例如,一个应该是另一个的成员)。书中的构造保证了这种行为。
例如,一个假设的游戏引擎需要声音和图形引擎才能工作,如果您在单独的编译单元中将它们声明为静态对象,并从另一个使用一个,则不能保证它不会失败,除非您以这种方式对它们进行编码你指定的。
参见 C++ faq输入问题的第二部分。
关于c++ - 对象初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5328447/