C++实现单例设计模式实战

C++实现单例设计模式实战,第1张

C++实现单例设计模式实战

singleton.h

#pragma once
#include 

//懒汉模式


template 
class Singleton 
{
public:
	static T* Instance()
	{
		if (_instance == nullptr)
		{
			std::unique_lock lock(_mutex);
			if (_instance == nullptr)//判断是否第一次调用
				_instance = new T();
		}
		return _instance;
	}

	static void Release()
	{
		if (_instance != nullptr)
		{
			delete _instance;
			_instance = nullptr;
		}
	}

protected:
	Singleton(void) {}
	virtual ~Singleton(void) {}

	static T* _instance;
	static std::mutex _mutex;
};

template  T* Singleton::_instance = nullptr;
template  std::mutex Singleton::_mutex;

main.cpp

#include "singleton.h"
#include 

using namespace std;

class Client : public Singleton {
public:
	void Init() {
		cout << "Init" << endl;
	}
};

int main()
{
	Client::Instance()->Init();

	return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5116049.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-17
下一篇2022-11-17

发表评论

登录后才能评论

评论列表(0条)

    保存