c++单例类

来源:互联网 发布:一品威客网 知乎 编辑:程序博客网 时间:2024/06/05 10:17
//singleton.h
#pragma once

template <typename T>
class Singleton
{
public:
template<typename... Args>
static T* Instance(Args&&... args)
{
if (m_pInstance == nullptr)
{
m_pInstance = new T(std::forward<Args>(args)...);
}
return m_pInstance;
}

static T* GetInstance()
{
if (m_pInstance == nullptr)
{
throw std::logic_error("Please initialize the instance first");
}
return m_pInstance;
}
static void DestroyInstance()
{
delete m_pInstance;
m_pInstance = nullptr;
}
private:
Singleton(void);
virtual ~Singleton(void);
//将拷贝构造函数和=操作符设置为私有的,禁止外在调用拷贝
Singleton(const Singleton&);
Singleton& operator = (const Singleton&);
private:
static T* m_pInstance;
};

template < class T> T* Singleton<T>::m_pInstance = nullptr;
////使用方式
//class A
//{
//public:
// void test(){};
//};
////使用方式
//Singleton<A>::Instance();
//Singleton<A>::GetInstance()->test();
//Singleton<A>::DestroyInstance();


0 0
原创粉丝点击