c++静态成员初始化

时间:2022-09-10 11:07:52
class A {
private:

static int a; //声明但未定义
static std::map<std::string,int>fileMap;

};

int A::a = 3; //定义了
std::map<std::string, int> YuvMap::fileMap = std::map<std::string, int>();

 

#include <iostream>
#include <map>
using namespace std;
 
class A
{
public:
    static map<int,int> m;
};
 
map<int,int> A::m;
 
int main()
{
    A::m.insert(make_pair(1,2));
 
    return 0;
}

 静态成员变量的初始化必须在类的外部

静态成员变量的析构,你不用管它就是了

 

1. static 成员程序退出前(main函数之后),会被析构,这种情况通常你不用管。
2. static指针成员,一般情况也不用去手动释放,除非代码依赖于这个指针所指向对象析构函数所带来的副作用。这时候,可以在确保这个被指向的对象绝对不会再被其他全局变量再使用的情况下,利用std::at_exit()来释放。有点复杂,你就先当做不需要释放就行了。