设计模式 单例模式 使用模板及智能指针

单例模式

// Singleton.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <memory>


using namespace std;

template< typename T >
class Singleton
{
public:
static std::shared_ptr<T> Instance();
private:
Singleton();
static std::shared_ptr<T> p;
};


template<typename T>
std::shared_ptr<T> Singleton<T>::p = nullptr;

template<typename T>
std::shared_ptr<T> Singleton<T>::Instance() {
if (p == nullptr) {
p = std::make_shared<T>();
}

return p;
}


int main()
{
std::shared_ptr<int> p = Singleton<int>::Instance();
std::cout << *p << " ";
return 0;
}

 

posted on 2017-09-01 09:32  itdef  阅读(303)  评论(0编辑  收藏  举报

导航