#include <assert.h>
namespace TT
{
template <typename T>
class Singleton
{
private:// 构造析构私有化
Singleton() {
assert(!mp_Singleton);
mp_Singleton = static_cast<T*>(this);
}
~Singleton() {
assert(mp_Singleton);
mp_Singleton = nullptr;
}
public://公开的接口
static T& Instance() {
if (!mp_Singleton)
mp_Singleton = new T();
return (*mp_Singleton);
}
protected:
static T* mp_Singleton;// 对象
};
template <typename T> T* Singleton<T>::mp_Singleton = nullptr;
}
运用实例
#include<iostream>
#include "singleton.h"
class MyClass
{
public:
MyClass() {};
~MyClass() {};
void prin() {
std::cout << "OK" << std::endl;
}
private:
};
#define mClass TT::Singleton<MyClass>::Instance()
int main(int argc, char * args[]) {
mClass.prin();
std::cin.get();
return 0;
}
static_cast 转换 :用隐式和用户定义转换的组合在类型间转换。
C++:Google base中的方法
namespace nbase
{
#define SINGLETON_DEFINE(TypeName) \
static TypeName* GetInstance() \
{ \
static TypeName type_instance; \
return &type_instance; \
} \
\
TypeName(const TypeName&) = delete; \
TypeName& operator=(const TypeName&) = delete
}