c++-单例模式Singleton

单例模式就是保证类只能有一个实例(因为现实中很多事物是独一无二的)

注意一下几点:

(1)构造函数设为私有(如果是公有的话,可以任意的调用构造函数),需要提供一个全局的访问点

(2)禁止拷贝操作,禁止=运算符操作

(3)当生命周期完了之后要自动调用析构函数,以免资源泄露(这里采用内部类的方式来实现)

1.借用内部类来实现单例的析构,线程不安全的

#include <iostream>

using namespace std;

class Singleton
{
public:
	static Singleton* GetInstance()
	{
		if(instance == NULL)
		{
			instance = new Singleton();
		}
		return instance;
	}

	class Garbo
	{
	public:
		~Garbo()
		{
			if(Singleton::instance != NULL)
			{
				delete instance;
			}
		}
	};
	~Singleton()
	{
		cout<<"destory"<<endl;
	}
private:
	Singleton()
	{
		cout<<"create"<<endl;
	}
	Singleton(Singleton &othoer)
	{

	}
	Singleton& operator=(Singleton &other)
	{

	}
	static Singleton *instance; //引用型说明
	static Garbo garbo;         //利用对象的确定行析构
};

Singleton *Singleton::instance;
Singleton::Garbo garbo;

int main()
{
	Singleton *s1 = Singleton::GetInstance();
	Singleton *s2 = Singleton::GetInstance(); //两个地址是相同的

	cout<<s1<<endl;
	cout<<s2<<endl;

}

2.上述实现要借用内部类,不是很完美,可以通过auto_ptr(我还没学)或者下面的方式实现

 这是最简单的,但是线程不安全的

#include <iostream>

using namespace std;

class Singleton
{
public:
	static Singleton& GetInstance()
	{
		static Singleton instance; //利用静态对象的不可重入性,第二次进入的时候是不执行这条语句的
		return instance;
	}

	~Singleton()
	{
		cout<<"destory"<<endl;
	}
private:
	Singleton()
	{
		cout<<"create"<<endl;
	}
	Singleton(Singleton &othoer)
	{

	}
	Singleton& operator=(Singleton &other)
	{

	}
};


int main()
{
	Singleton &s1 = Singleton::GetInstance(); //这里必须是引用
	Singleton &s2 = Singleton::GetInstance(); //两个地址是相同的

	cout<<&s1<<endl;
	cout<<&s2<<endl;

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值