版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/river472242652/article/details/82979009
##基本模板类
#pragma once
#include <iostream>
#include <thread>
using namespace std;
/**
*Meyers 方案(利用语言级别的静态成员属性来实现)
* 1优化了 判断消耗,
* 2优化了释放实例,不会导致内存泄露
* 3多线程下保证一个实例(但是并不是真正意义的线程安全实现--vs2010以上可以保证成员属性的初始化完成)
*Date :[10/9/2018 ]
*Author :[RS]
*/
template<typename T>
class SingletonTmp {
protected:
SingletonTmp() {
cout << "begin" << endl;
this_thread::sleep_for(chrono::seconds(1));
cout << "end" << endl;
}
~SingletonTmp() {
cout << "析构" << endl;
}
public:
//单例对象使用局部静态变量的方法,从而延迟到调用时实例化
static T& GetInstance() {
static T instacne;
return instacne;
}
private:
SingletonTmp(const SingletonTmp&) = delete;
SingletonTmp* operator=(const SingletonTmp&) = delete;
};
具体类
#pragma once
#include "SingletonTmp.h"
class Manager2 :public SingletonTmp<Manager2> {
friend class SingletonTmp<Manager2>;
protected:
Manager2() {
cout << "manager2" << endl;
}
~Manager2() = default;
private:
Manager2(const Manager2 &) = delete;
Manager2& operator=(const Manager2&) = delete;
public:
private:
};
使用
#include "Manager2.h"
void fun() {
Manager2::GetInstance();
}
void main() {
thread t(fun);
thread t2(fun);
thread t3(fun);
t.join();
t2.join();
t3.join();
system("pause");
}