共享指针 ,因为要在外外部创建,构造函数必须是pulic
#define DECLARE_SINGLETON(classname) \
public: \
static classname *instance() { \
static std::shared_ptr<classname> instance_cached = nullptr; \
if (instance_cached == nullptr) { \
static std::once_flag flag; \
std::call_once( \
flag, [&] { instance_cached = std::make_shared<classname>(); }); \
} \
return instance_cached.get(); \
} \
\
private:
常规
#pragma once
/*
* @brief :定义单例类宏
*/
#include <mutex>
#define DISABLE_COPY(Class) \
Class(const Class&) = delete; \
Class& operator=(const Class&) = delete;
#define SINGLETON_DECL(Class) \
public: \
static Class* instance(); \
static void exitInstance(); \
private: \
DISABLE_COPY(Class) \
static Class* s_pInstance; \
static std::mutex s_mutex;
#define SINGLETON_IMPL(Class) \
Class* Class::s_pInstance = NULL; \
std::mutex Class::s_mutex; \
Class* Class::instance() { \
if (s_pInstance == NULL) { \
s_mutex.lock(); \
if (s_pInstance == NULL) { \
s_pInstance = new Class; \
} \
s_mutex.unlock(); \
} \
return s_pInstance; \
} \
void Class::exitInstance() { \
s_mutex.lock(); \
if (s_pInstance) { \
delete s_pInstance; \
s_pInstance = NULL; \
} \
s_mutex.unlock(); \
}
头文件:SINGLETON_DECL(Aclass)
实现文件:SINGLETON_IMPL(Aclass)
通用模板
template<class T>
class Singleton
{
public:
static T& instance(){
static T theInstance;
return theInstance;
}
protected:
Singleton(){}
virtual ~Singleton(){}
private:
// Singleton(const Singleton&);
// Singleton& operator =(const Singleton&);
};
//单例类
class MyClass : public Singleton<MyClass>
{
public:
void setValue(int n){x = n;}
int getValue(){return x;}
protected:
friend class Singleton<MyClass>;
MyClass(){x = 0;}
private:
~MyClass();
int x;
};
int main()
{
MyClass& m = MyClass::instance();
cout << m.getValue() << endl;
m.setValue(1);
cout << m.getValue() << endl;
return 0;
}