简体   繁体   中英

How static object gets initialized at compile time?

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

void fun() {
    static Bird 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

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.

No. The memory is already allocated at compile time (before the program gets executed). It's just that initialization happens when the execution touches the static Bird obj; statement. This is called lazy initialization .

Also, note that, in case if Bird() constructor throws an exception, then the initialization will not be finished. So again when the fun() is called, obj is again tries to get initialized. It happens until the obj initializes successfully. After that, that line will not be executed any more.

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.

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.

static initialization does not happen at compile time. It happens at run-time, but before main() is invoked.

The order in which static initialization spread across compilation units is not defined. Hence, if you really need static variables, the recommended way is to put all of them on a single static_constructors.cpp, and as a extra benefit, they'll be easier to find

In that situation, static has a different meaning. It means that obj will be initialized only once, at the first time fun() is called and obj will remaing valid between calls to fun() .

Think of it as a global variable, but only the function fun() can see it:P

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM