#include "stdafx.h"
#include<iostream>
using namespace std;
class singleton1 //懒汉模式
{
public:
static singleton1 *getInstance()
{
if(NULL == m_instance1)
{
//Lock(); 可自己实现Lock类,或使用boost库中的
if(NULL == m_instance1)
{
m_instance1 = new singleton1();
cout<<"singleton1 created!"<<'\n';
}
//Ulock();
}
return m_instance1;
}
static void destoryInstance()
{
if(NULL != m_instance1)
{
delete m_instance1;
m_instance1 = NULL;
cout<<"delete singleton1"<<'\n';
}
}
private:
static singleton1 * m_instance1;
singleton1(){};
};
singleton1 * singleton1::m_instance1 = NULL; //new singleton1();//懒汉式
class singleton2 //饿汉模式
{
public:
static singleton2 *getInstance()
{
//因为静态初始化在程序开始时,也就是进入主函数之前,由主线程以单线程方式完成了初始化,
//所以静态初始化实例保证了线程安全性。
static singleton2 instance2; //局部静态变量
cout<<"singleton2 created!"<<'\n';
return &instance2;
}
private:
singleton2(){};
};
class singleton3 //解决懒汉式的内存泄漏问题
{
public:
static singleton3 * getInstance()
{
if(NULL == m_instance3)
{
//Lock(); 可自己实现Lock类,或使用boost库中的
if(NULL == m_instance3)
{
m_instance3 = new singleton3();
cout<<"singleton3 created!"<<'\n';
}
//Ulock();
}
return m_instance3;
}
private:
singleton3(){}
static singleton3 * m_instance3;
class Gc
{
private:
~Gc()
{
if(m_instance3 != NULL)
{
delete m_instance3;
m_instance3 = NULL;
cout<<"delete m_instance3";
}
}
};
static Gc Gc;//定义一个静态成员变量,程序结束时,系统会自动调用它的析构函数
};
singleton3 * singleton3::m_instance3 = NULL;
int main()
{
singleton1 * instance1_1 = singleton1::getInstance();
singleton1 * instance1_2 = singleton1::getInstance();
if(instance1_1 == instance1_2)
cout<<"instance1_1 == instance1_2"<<'\n';
singleton2 * instance2_1 = singleton2::getInstance();
singleton2 * instance2_2 = singleton2::getInstance();
if(instance2_1 == instance2_2)
cout<<"instance2_1 == instance2_2"<<'\n';
singleton3 * instance3_1 = singleton3::getInstance();
singleton3 * instance3_2 = singleton3::getInstance();
if(instance3_1 == instance3_2)
cout<<"instance3_1 == instance3_2"<<'\n';
instance1_1->destoryInstance(); //手动delete,instance1_1
//instance2_1 在程序结束后会自动析构
//instance3_1 在程序运行结束时,系统会调用singleton3的静态成员Gc的析构函数,该析构函数会进行资源的释放
while(1);
return 0;
}
C++单例模式
最新推荐文章于 2024-11-12 14:48:32 发布