> C的初始化顺序是:
零初始化
>静态初始化;
>动态初始化.
>静态对象(包含变量)首先被零初始化,然后静态初始化.
关于初始化问题,我有几个查询(存储类问题也可能相关):
>全局对象(没有静态关键字定义)也是静态对象,对吧?
>全局对象也像静态对象一样通过两个步骤进行初始化,如上所述,对吗?
>什么是静态初始化?是指初始化静态对象(用static关键字定义)吗?
>我还读取当执行线程首次进入块时初始化具有static关键字的块内定义的对象(即函数中).这意味着在主函数执行之前,本地静态对象不被初始化.这意味着它们没有被初始化为上述两个步骤,对吧?
>动态初始化是指由新操作符创建的对象的初始化,对吗?它可能引用初始化像myClass obj = myClass(100);或者myClass obj = foo();
我对初始化和存储类说明符的问题有太多的查询.我阅读了C 2003标准文档,但是由于它们分散在整个文档中,因此找不到明确的逻辑.
我希望你给我一个答案,逻辑上解释了存储类说明符和初始化的整个映射.欢迎任何参考!
可能解释我的问题的代码:
class myClass{ public: int i; myClass(int j = 10): j(i){} // other declarations }; myClass obj1;//global scope static myClass obj2(2);//file scope { //local scope myClass obj3(3); static myClass obj4(4); }
编辑:
如果您认为我的问题相当乏味,您可以根据上述代码解释您的想法.
解决方法
I read several posts on C++ initialization from Google,some of which direct me here on StackOverflow. The concepts I picked from those posts are as follows:
- The order of initialization of C++ is:
- Zero Initialization;
- Static Initialization;
- Dynamic Initialization.
是的,确实有3个阶段(在标准中).让我们在继续之前澄清一下:
>零初始化:存储器在字节级填满0.
>常量初始化:预计算(编译时)字节模式被复制在对象的内存位置
>静态初始化:零初始化,然后进行常量初始化
>动态初始化:执行一个函数来初始化内存
一个简单的例子:
int const i = 5; // static initialization int const j = foo(); // dynamic initialization
- Static objects (variables included) are first Zero-initialized,and then Static-initialized.
是和否
标准要求对象首先被初始化,然后它们是:
>如果可能,常量初始化
>否则动态地初始化(编译器无法计算内存内容)
注意:在常量初始化的情况下,编译器可能会忽略根据as-if规则的第一个零初始化的内存.
I have several inquiries as to the initialization issue (storage class issue may be related as well):
- Global objects (defined without static keyword) are also static objects,right?
是的,在文件范围内,静态对象就是符号的可见性.全局对象可以通过名称从另一个源文件引用,而静态对象名称对于当前源文件是完全本地的.
混乱源于许多不同情况下的世界静态的重用:
- Global objects are also initialized like static objects by two steps like above,实际上是本地的静态对象.
- What is the Static Initialization? Does it refer to initializing static objects (defined with static keyword)?
不,它是指在不执行用户定义的函数的情况下初始化对象,而是将预先计算的字节模式复制到对象的内存上.请注意,在稍后将动态初始化的对象的情况下,这只是使内存为零.
- I also read that objects defined within block (i.e. in a function) with static keyword is initialized when the execution thread first enters the block! This means that local static objects are not initialized before main function execution. This means they are not initialized as the two steps mentioned above,right?
它们通过两个步骤进程进行初始化,尽管实际上只有第一次执行通过它们的定义.所以这个过程是一样的,但时间却是微乎其微.
实际上,如果它们的初始化是静态的(即,存储器模式是编译时模式),并且它们的地址不被采用,那么它们可以被优化掉.
请注意,在动态初始化的情况下,如果它们的初始化失败(假定初始化它们的函数抛出异常),下一次流控制将通过它们的定义重新尝试.
- Dynamic initialization refers to initialization of objects created by new operator,right? It might refer to initialization like
myClass obj = myClass(100);
ormyClass obj = foo();