Understand static/global data completely in C++

Static/globa data

Lifecycle:
All static data and global data would be stored in static/global storage area for the whole application. Dll's static and global data would be there of course. In general, two notes:
When loading dll, before entering dllMain, static and global data will be initialized. If later the dll can be freed from application process, all these data will be removed away from application static/global area.
If the dll would not be unloaded, since the data is in global area, so they will live the same length as the application.

Type:
对于全局变量而言,不论是普通全局变量还是static全局变量,其存储区都是静态存储区,因此在内存分配上没有什么区别。
C++的static有两种用法:面向过程程序设计中的static和面向对象程序设计中的static。前者应用于普通变量和函数,不涉及类;后者主要说明static在类中的作用。
1. Normal global data
普通的全局变量和函数,其作用域为整个程序或项目,外部文件(其它cpp文件)可以通过extern关键字访问该变量和函数。如果要在多个cpp文件间共享数据,应该将数据声明为extern类型。     

在头文件里声明为extern:
extern int g_value;     // 注意,不要初始化值!

然后在其中任何一个包含该头文件的cpp中初始化(一次)就好:

int g_value = 0;     // 初始化一样不要extern修饰,因为extern也是声明性关键字;

然后所有包含该头文件的cpp文件都可以用g_value这个名字访问相同的一个变量。

2. static global data
static变量,不管是局部还是全局,都存放在静态存储区。
static全局变量和函数,其作用域为当前cpp文件,其它的cpp文件不能访问该变量和函数。如果有两个cpp文件声明了同名的全局静态变量,那么他们实际上是独立的两个变量。static函数的好处是不同的人编写不同的函数时,不用担心自己定义的函数,是否会与其它文件中的函数同名。

Attention:头文件中的static变量如果在一个头文件中声明:

static int g_vaule = 0;

那么会为每个包含该头文件的cpp都创建一个全局变量,但他们都是独立的;所以也不建议这样的写法,一样不明确需要怎样使用这个变量,因为只是创建了一组同名而不同作用域的变量。

3. OO: static member data (easy)


原文地址:https://www.cnblogs.com/taoxu0903/p/1431278.html