Skip to content

Instantly share code, notes, and snippets.

@DamonHao
Last active July 1, 2017 13:44
Show Gist options
  • Select an option

  • Save DamonHao/a93a5d3f65d39104b4a1 to your computer and use it in GitHub Desktop.

Select an option

Save DamonHao/a93a5d3f65d39104b4a1 to your computer and use it in GitHub Desktop.
C++ 类的static成员变量和函数内static变量初始化时机
/*
C++ static 变量初始化时间就和普通static的初始化时间是一样的。
*/
#include <iostream>
using namespace std;
class A
{
public:
A(){cout<<1<<endl;}
};
class B
{
public:
static A a;
};
A B:: a; //有了这一句静态变量a才会初始化
int main()
{
// B b;
return 0;
}
/*
C++ 函数内static 变量的初始化发生在第一次调用函数的时候。
*/
#include <iostream>
using namespace std;
class A
{
public:
A(){cout<<1<<endl;}
};
void func()
{
static A a;
}
int main()
{
func();
func();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment