c++ Initialization

c++ 的初始化过程比较复杂:根据对象的storage duration来分类。所谓storage duration是对象而言的,Storage duration is the property of an object that defines the minimum potential lifetime of the storage containing the object。跟lifetime密切相关,但是lifetime是具体的对象生存期。而storage duration是生存期的类型。一个是抽象的概念,一个是具体的概念,属于正交。

All non-local variables with static storage duration are initialized as part of program startup, before the execution of the main function begins. non-local 对象包括global variable, non-local static variable, namespace variable. 

其中non local static duration的variable的初始化规则有: 

1. zero Initialization:也就是初始化为0

2. const Initialization:如果是int i=4,那么在编译期就初始化了

以上都属于static Initialization初始化.

After all static initialization is completed, dynamic initialization of non-local variables occurs in the following situations:

int i=func()

那么non-loca static duration的variable变量呢,只有local scope的static 局部变量,它什么时候初始化?c++标准规定:

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). On all further calls, the declaration is skipped.

这就是惰性初始化

以上区分的关键点是static duration是否是non-local

 

那么根据external linkage 还是internal linkage 判断是否被不同的编译单元可见: global variable是有external的属性的。namespace的global variable也是。还有就是function函数默认是external的

  • names of variables declared extern;
  • names of functions

那么常见的static修饰的变量和函数都是internal linkage的:

  • variables, functions, or function templates declared static;

 

归纳static关键字的作用:

static class member    static class function     static object(non-local and local)   static normal function

 

// inside some .cpp file:

static void foo();    // old "C" way of having internal linkage

// C++ way:
namespace
{
   void this_function_has_internal_linkage()
   {
      // ...
   }
}
 
View Code

 

 

 


 

 

posted @ 2019-03-15 16:06  kkshaq  阅读(318)  评论(0编辑  收藏  举报