class CSingleton
{
private:
CSingleton() //构造函数是私有的
{
}
static CSingleton *m_pInstance;
public:
static CSingleton * GetInstance()
{
if(m_pInstance == NULL) //判断是否第一次调用
m_pInstance = new CSingleton();
return m_pInstance;
}
};
使用shared_prt来解决这个问题
// ConsoleApplication4.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<string>
#include<map>
#include<vector>
#include<memory>
using namespace std;
class B
{
public :
B(int b){ _b = b; }
int _b;
~B()
{
cout << "释放B"<< _b << endl;
}
};
class Singleton
{
public:
~Singleton()
{
cout << "释放singleton" << endl;
}
private:
Singleton(){
};
private:
static shared_ptr<Singleton> _instance;
public:
static shared_ptr<Singleton> getInstance();
void printCode()
{
cout << "i am printing" << std::endl;
}
vector<B*> bs;
};
shared_ptr<Singleton> Singleton::_instance = nullptr;
shared_ptr<Singleton> Singleton::getInstance()
{
if (_instance == nullptr)
_instance = shared_ptr<Singleton>(new Singleton());
return _instance;
}
void testSingleton()
{
auto s = Singleton::getInstance();
B b3 (3);
s->bs.push_back(&b3); //b3 出函数后会被销毁,所以出了该作用域之后的b调用会有大问题
for each (auto var in s->bs)
{
cout << var->_b << endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
shared_ptr<Singleton> s = Singleton::getInstance();
s->printCode();
B b1 = B(1);
B b2 = B(2);
testSingleton();
s->bs.push_back(&b1);
s->bs.push_back(&b2);
for each (auto var in s->bs)
{
cout << var->_b << endl;
}
return 0;// Main函数调用结束之后 Singleton的实例会被回收,其资源也会被回收
}