[英]When is constructor called for a static object
I understand that static variables are initialized at compile time, but what about a static object? 我知道静态变量是在编译时初始化的,但静态对象呢?
eg if I have the following code: 例如,如果我有以下代码:
class A {
A();
};
A::A(){
std::cout << "Constructing A" << std::endl;
}
int main(){
std::cout << "Hello World!" << std::endl;
static A A_obj;
std::cout << "Goodbye cruel world" << std::endl;
return 0;
}
Should I expect the output to be: 我应该期望输出是:
Hello World!
Constructing A
Goodbye cruel world
or 要么
Constructing A
Hello World!
Goodbye cruel world
"I understand that static variables are initialized at compile time"
“我知道静态变量在编译时被初始化”
Not true. 不对。
static
variables at function scope are strictly initialised at the point of first encounter. 函数范围的
static
变量在第一次遇到时严格初始化。 And will be destructed after the closing brace of main
. 并将在
main
的闭合支撑后被破坏。
You'll get output in this order: 您将按此顺序获得输出:
Hello World!
Constructing A
Goodbye cruel world
According to cppreference : 根据cppreference :
Variables declared at block scope with the specifier static have static storage duration but are initialized the first time control passes through their declaration (unless their initialization is zero- or constant-initialization, which can be performed before the block is first entered).
在块作用域中使用指定符static声明的变量具有静态存储持续时间,但是在控件第一次通过其声明时初始化(除非它们的初始化为零或初始化初始化,这可以在首次输入块之前执行)。 On all further calls, the declaration is skipped.
在所有进一步的调用中,将跳过声明。
Meaning the constructor is called as soon as the declaration is seen for the class. 这意味着只要为类看到声明,就会调用构造函数。 Furthermore:
此外:
The destructor for a block-scope static variable is called at program exit , but only if the initialization took place successfully.
在程序退出时调用块范围静态变量的析构函数 ,但仅在初始化成功发生时才调用 。
Since the program exit is at the end of the function main()
, once your program reaches the end of main()
, the destructor of your class will be called. 由于程序退出位于函数
main()
的末尾,一旦程序到达main()
的末尾,将调用类的析构函数。
Thus, you should expect the first output for the program. 因此,您应该期望该程序的第一个输出。
I understand that static variables are initialized at compile time, but what about a static object?
我知道静态变量是在编译时初始化的,但静态对象呢?
That's an incorrect understanding. 这是一个错误的理解。
Any variable, static
or not, can be evaluated at compile time if that's possible. 如果可能的话,可以在编译时评估任何变量(
static
或非static
。 Some are required to be evaluated at compile time. 有些需要在编译时进行评估。 Some cannot be evaluated at compile time, and hence must be initialized at run time.
有些在编译时无法进行评估,因此必须在运行时进行初始化。 Once again, that does not depend on whether a variable is
static
or not. 再一次,这不取决于变量是否是
static
。
Coming to your code, you should expect the first block of output. 来到你的代码,你应该期待第一个输出块。
The code to initialize A_obj
is executed after the previous line has been executed. 初始化
A_obj
的代码在执行上一行之后执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.