global-local-static-object

时间:2023-03-09 18:09:51
global-local-static-object

【本文链接】

http://www.cnblogs.com/hellogiser/p/global-local-static-object.html

【分析】

1.生命周期问题:static变量在固定的内存区域进行存储分配,变量生命期一直到程序运行结束。而普通变量:局部变量和全局变量的存储分配在不同的地方进行,局部变量是在堆栈里面存储分配,变量生命周期随着函数的退出而结束;全局变量是在静态存储区存储分配(跟static变量一样)。

2.可见性问题:一个类里面的static变量在类外是不可见的;函数内部的static变量在函数外是不可见的;函数外的static变量只在当前编译单元可见。

3.初始化问题:全局static变量在main函数运行前初始化;局部static变量在第一次所在函数被调用时初始化。对于内部类型,字符类型初始化为ascii值为0的字符,其他类型初始化为0;用户定义类型,要由构造函数初始化。

注:如果一个包含局部static对象的函数未被调用,那么这个对象的构造函数也不会被调用。

4.静态对象的析构函数调用:在程序从main()中退出时,或者标准的C库函数exit()函数被调用时才被调用。调用abort()退出程序时,静态对象的析构函数并不会被调用。静态对象的销毁也是按与初始化时相反的顺序进行的。

【代码】

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
 
/*
    version: 1.0
    author: hellogiser
    blog: http://www.cnblogs.com/hellogiser
    date: 2014/9/20
*/

#include "stdafx.h"
#include "iostream"
using namespace std;

class MyClass
{
    char c;
public:
    MyClass(char cc): c(cc)
    {
        cout << "MyClass::MyClass() for " << c << endl;
    }
    ~MyClass()
    {
        cout << "MyClass::~MyClass() for " << c << endl;
    }
};

static MyClass a ('a'); // global static
void f()
{
    static MyClass b('b'); // local static
}

void g()
{
    static MyClass c('c'); // local static
}

int main()
{
    cout << "inside main()" << endl;
    f();
    static float f; // local static  initialized with 0
    static int i;   // local static  initialized with 0
    cout << "float f:" << f << endl;
    cout << "int i:" << i << endl;
    cout << "leaving main()" << endl;

;
}
/*
MyClass::MyClass() for a
inside main()
MyClass::MyClass() for b
float f:0
int i:0
leaving main()
MyClass::~MyClass() for b
MyClass::~MyClass() for a
*/

【参考】

http://www.cnblogs.com/liujiangyi/archive/2012/08/13/2635840.html