C++之单例模式代码实现

来源:互联网 发布:网络信息安全重大事件 编辑:程序博客网 时间:2024/05/17 22:12


template <typename Type>
class Singleton
{
public:
 static Type* getInstance()
 {
  if (!_instance)
  {
   unique_lock<mutex> lock(_mutex);
   if (!_instance)
    _instance = make_unique<Type>();
  }
  return _instance.get();
 }
private:
 static unique_ptr<Type> _instance;
 static mutex _mutex;
};

#define IMPLEMENT_SINGLETON(Type) \
unique_ptr<Type> Singleton<Type>::_instance; \
mutex Singleton<Type>::_mutex;
原创粉丝点击