c++ 单例模式--双重校验+锁--懒汉式[4]**推荐

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/river472242652/article/details/82980811

基本类

#include <memory>
#include <mutex>
using namespace std;
template<typename T>
class SingletonPtr {
private:
	class Delete {
	public:
		void operator()(T *p) {
			delete p;
		}
	};
protected:
	SingletonPtr() = default;
	virtual ~SingletonPtr() {
		cout << "SingletonPtr" << endl;
	};
	SingletonPtr(const SingletonPtr&) = delete;
	SingletonPtr& operator=(const SingletonPtr&) = delete;
public:
	static T& GetInstance() {
		static mutex mMutex;
		if (nullptr==instance){
			{
				lock_guard<mutex> lock(mMutex);
				if (nullptr == instance) {
					shared_ptr<T> temp(new T(), T::Delete());
					instance = temp;
					return *instance.get();
				}
			}
			return *instance.get();

		}
		return *instance.get();

	}
private :
	static shared_ptr<T> instance;
};
template<typename T>
shared_ptr<T> SingletonPtr<T>::instance=nullptr;

单例类

#pragma once
#include "SingletonPtr.hpp"
#include <iostream>
class Manager :public SingletonPtr<Manager> {
	friend class SingletonPtr<Manager>;
protected:
	Manager() {
		cout << "manager start" << endl;
		this_thread::sleep_for(chrono::seconds(1));
		count = 12;
		cout << "manager end" << endl;
	}
public:
	~Manager() {
		cout << "manager析构" << endl;
	};
	Manager(const Manager&) = delete;
	Manager& operator=(const Manager&) = delete;
public:
	void Print() {
		cout << this_thread::get_id() << "-" << count << endl;
	}
private:
	int count;
};

入口文件

#include "Manager.hpp"

void fun() {
	Manager::GetInstance().Print();
}

void main() {
	cout.sync_with_stdio(true);
	thread t(fun);
	thread t2(fun);
	thread t3(fun);
	t.join();
	t2.join();
	t3.join();
	system("pause");
}

测试结果
测试结果

猜你喜欢

转载自blog.csdn.net/river472242652/article/details/82980811