单例模式定义
保证一个类仅有一个实例,并提供一个该实例的全局访问点。
——《设计模式》
代码一
#include <stdlib.h>
using namespace std;
class Singleton {
public:
static Singleton* GetInstance(){
if(_instance == nullptr){
_instance = new Singleton();
}
return _instance;
}
private:
Singleton(){
}; //普通构造
~Singleton(){
};
Singleton(const Singleton &) = delete; //拷贝构造
Singleton& operator=(const Singleton &) = delete; //拷贝赋值构造
Singleton(Singleton &&) = delete; //移动构造
Singleton& operator=(Singleton &&) = delete; //移动拷贝构造
static Singleton *_instance;
}
Singleton* Singleton::_instance = nullptr;
代码一说明
在单例模式中,为了确保一个类对应一个实例,不仅要考虑只能创建一个实例,而且要考虑创建一个实例后,这个实例又被调用去创建另一个实例。所以,要将普通构造和析构函数设置为私有,然后禁用四类特殊构造函数。在这里就使用了c++11的新特性:Singleton(const Singleton &) = delete,可以实现将某个构造函数禁用的功能。
代码一的问题
没有安全地释放内存,而且私有的析构函数不能在外部调用,无法灵活地释放动态内存,容易造成内存泄漏,所以需要加一个静态的释放内存的接口。
代码二
#include <stdlib.h>
using namespace std;
class Singleton {
public:
static Singleton* GetInstance(){
if(_instance == nullptr){
_instance = new Singleton();
atexit(Destructor);
}
return _instance;
}
private:
static void Destructor(){
if(nullptr != _instance){
delete _instance;
_instance = nullptr;
}
}
Singleton(){
}; //普通构造
~Singleton()