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);
}
原文:https://www.cnblogs.com/adorkable/p/10529965.html