类的静态成员变量指针,如何释放?
目前有两种方法:
- 智能指针
- 使用静态变量维护一个引用计数,每创建一个对象,引用计数加1,析构函数中,引用计数减一,直到为0才释放内存
//方法一:使用智能指针
//使用智能指针在程序结束时(main大括号之外)会弹出结束对话框,使用普通指针不会弹出
#include <iostream>
#include <memory>
#include <Windows.h>
using namespace std;
class A
{
public:
A()
{
MessageBox(GetForegroundWindow(), "", "【创建】", 1);
}
~A()
{
cout << "delete" << endl;
MessageBox(GetForegroundWindow(), "", "【结束】", 1);
}
};
class B
{
public:
B()
{
};
~B()
{
};
private:
static std::shared_ptr<A> m_instance;
//static A* m_instance;
};
std::shared_ptr<A> B::m_instance = std::shared_ptr<A>(new A());
//A* B::m_instance = new A();
int main()
{
B b;
B b1;
B b2;
B b3;
return 0;
}
//方法二:参考链接:https://blog.csdn.net/vgxpm/article/details/47048873
//使用静态变量维护一个引用计数,每创建一个对象,引用计数加1,
//析构函数中,引用计数减一,直到为0才释放内存
#include<iostream>
using namespace std;
class A
{
public:
A()
{
cout << "create" << endl;
}
~A()
{
cout << "delete" << endl;
}
};
class B
{
public:
B()
{
if (m_instance == NULL)
{
m_instance = new A();
}
++m_count;
cout << m_count << endl;
};
~B()
{
--m_count;
cout << m_count << endl;
if (m_instance != NULL && m_count == 0)
{
delete m_instance;
m_instance = NULL;
}
};
private:
static A* m_instance;
static int m_count;
};
A* B::m_instance = new A();
int B::m_count = 0;
int main()
{
B b;
B b1;
B b2;
B b3;
return 0;
}