如何静态对象在编译时被初始化? [英] How static object gets initialized at compile time?

查看:96
本文介绍了如何静态对象在编译时被初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Bird {
public:
   Bird() {
     .....
     .....
    }    
};

void fun() {
    static Bird obj;
}

当编译器编译语句 static Bird obj 做2事。首先是对象obj的内存分配。第二是通过调用构造函数初始化obj。我的问题是如果初始化部分发生在编译时,如何在编译时执行构造函数中的所有语句

When compiler compiles the statement static Bird obj It does 2 thing. First is memory allocation for object obj. Second is initialization of obj by calling constructor. My question is if initialization part happens in compile time, how all the statement inside constructor will be executed at compile time

推荐答案

时间,编译器将在作为程序空间一部分的特殊静态对象区域中留出一块内存。

At compile time, the compiler will set aside a chunk of memory in a special static object area which is part of the program space. That memory will be uninitialized.

在函数内部,编译器将放置一个不可见的if语句,该语句检测静态对象语句是否第一次被执行。如果是第一次,将调用对象的构造函数。

Inside the function, the compiler will put an invisible "if" statement which detects that the static object statement is being executed for the first time. If it is the first time, the constructor for the object will be called.

这篇关于如何静态对象在编译时被初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆