上一篇的单例模式是非线程安全的,为什么呢?试想一下,当两个线程同时初次调用getInstance()方法时,会导致产生多个实例。这里我们采用饱汉模式(在初始化的时候就给定getInstance()生成相应的实例,由于我们声明在静态存储区,在函数最开始的时候就会被生成,也就不存在后续的线程竞争,这是最简单的一种方法)另外我们使用atexit()函数使得程序在退出时自动实现内存回收。
#include <stdlib.h>
#include <iostream>
#include <stdio.h>
//using namespace std;
//让单例类对象自动释放
//版本二: atexit + 饱汉式
class Singleton
{
public:
static Singleton * getInstance()
{
if(_pInstance == NULL)
{
_pInstance = new Singleton;
atexit(distroy);
}
return _pInstance;
}
static void distroy()
{
if(_pInstance)
delete _pInstance;
std::cout << "distroy()" << std::endl;
}
private:
Singleton(){}
~Singleton(){}
private:
static Singleton * _pInstance;
};
Singleton * Singleton::_pInstance = getInstance();
int main(int argc, char const *argv[])
{
Singleton::getInstance();
return 0;
}