C++11出来后,里面新增加了好多好用的功能
下面的单例就是使用了C++11中的标准库中的mutex和unique_prt 进行内存管理的.
此单例模式不用担心内存的释放问题
1#pragma once 2#include <memory> 3#include <mutex> 4 5 6template <class T> 7class Singleton 8{ 9public: 10 typedef typename std::unique_ptr<T> handleType; 11public: 12 static handleType& GetInstance() 13 { 14 if (!ms_inst) 15 { 16 std::mutex m; 17 std::lock_guard<std::mutex> lock(m); 18 19 ms_inst.reset(new T); //不要写成了ms_inst->reset(new T); 20 21 } 22 23 return ms_inst; 24 } 25 26//需要使用protected 关键字,不能使用private 27protected: 28 Singleton(){} 29 Singleton(const Singleton& inst){} 30 Singleton& operator=(const Singleton& inst){} 31 32private: 33 static handleType ms_inst; 34};
//下面的初始化需要加 typename template<class T> typename Singleton<T>::handleType Singleton<T>::ms_inst;
