C++ static变量的生命周期?上次被问到这个问题,本来以为自己很了解,但对于何时创建,我却徘徊在“main函数之前”和“第一次执行”之间……不能做出一个肯定的回答。以下就对这个问题做详细的分析。
static变量有以下几类:
1. 全局static变量
2. 命名空间内的static变量
3. 类的static变量
4. 函数体内的static变量
对于以上1、2、3类,static变量在程序启动时,即main函数之前创建(分配内存),在程序结束时释放。
对于第4类,在第一次执行到该static变量的定义时创建,在程序结束时释放;如果程序一直没执行到该static变量的定义,则一直不会创建,也当然不会释放。
测试代码如下:
1. 全局static变量
2. 命名空间内的static变量
class A
{
public:
A() { cout << "A::A()" << endl; }
~A() { cout << "A::~A()" << endl; }
};
static A a;
namespace NS
{
class B
{
public:
B() { cout << "B::B()" << endl; }
~B() { cout << "B::~B()" << endl; }
};
static B b;
}
int main(int argc, char* argv[])
{
cout << "main begin" << endl;
system("pause");
cout << "main end" << endl;
return 0;
}
输出:
A::A()
B::B()
main begin
main end
B::~B()
A::~A()
3. 类的static变量
class A
{
public:
A() { cout << "A::A()" << endl; }
~A() { cout << "A::~A()" << endl; }
};
class B
{
static A a;
};
A B::a;
int main(int argc, char* argv[])
{
cout << "main begin" << endl;
system("pause");
cout << "main end" << endl;
return 0;
}
输出:
A::A()
main begin
main end
A::~A()
4. 函数体内的static变量
class A
{
public:
A() { cout << "A::A()" << endl; }
~A() { cout << "A::~A()" << endl; }
};
void func()
{
cout << "func start" << endl;
static A a;
cout << "func end" << endl;
}
int main(int argc, char* argv[])
{
cout << "main begin" << endl;
func();
system("pause");
cout << "main end" << endl;
return 0;
}
输出:
main begin
func start
A::A()
func end
main end
A::~A()
如果不调用func(),则不会输出A::A()和A::~A()