C++ 宏定义创建(销毁)单例
Util.h:
#define CREATE_SINGLETON_POINTER(CLASS,INSTANCE,MUTEX) if (NULL == INSTANCE) \ { \ MUTEX.lock(); \ if (NULL == INSTANCE) \ { \ INSTANCE = new CLASS(); \ } \ MUTEX.unlock(); \ } #define DESTORY_SINGLETON_POINTER(INSTANCE) if (NULL != INSTANCE) \ { \ delete INSTANCE; \ INSTANCE = NULL; \ }
Foo.cpp:
#include "Foo.h" #include <mutex> std::mutex instanceMutex; Foo* Foo::instance = NULL; Foo* Foo::getInstance() { CREATE_SINGLETON_POINTER(Foo, instance, instanceMutex); return instance; }
Foo::~Foo()
{
DESTORY_SINGLETON_POINTER(instance);
}