问题描述
在切换到C ++之前,我们发现Delphi中的初始化化
语言元素非常有用。它允许您在程序启动时在每个单元中都有代码,因此您可以初始化该单元的各个元素。
Before switching to C++, we found the initialization
language element in Delphi extremely useful. It allowed you to have code in each unit which would be called when the program was started, so you could initialize various elements of that unit.
-
所以为什么没有
初始化$在C ++中c $ c>和
最终化
?
我们有哪些替换此语言功能的选项?在C ++中?
What are our options for replacements of this language feature in C++?
推荐答案
等效的C ++功能是文件的构造函数和析构函数-scope /全局对象。例如:
The equivalent C++ feature is constructors and destructors for file-scope/global objects. For instance:
#include <iostream>
using std::cout;
struct X {
X() { cout << "X::X()\n"; }
~X() { cout << "X::~X()\n"; }
};
static X x;
int main() { cout << "main()\n"; return 0; }
将输出
X::X()
main()
X::~X()
运行时。
使用此功能通常被认为是不明智的,因为您无法控制这些构造函数的顺序。并且执行了析构函数,这意味着事情可能在依赖它们之前就被初始化了,从而导致难以调试的崩溃。
It is generally considered unwise to use this feature, because you have no control whatsoever over the order in which these constructors and destructors are executed, which means things may get initialized before their dependencies, producing hard-to-debug crashes.
这篇关于为什么没有“初始化”? C ++中的关键字,就像在Delphi中一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!