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"#includestd::mutex instanceMutex;Foo* Foo::instance = NULL;Foo* Foo::getInstance(){ CREATE_SINGLETON_POINTER(Foo, instance, instanceMutex); return instance;} Foo::~Foo() { DESTORY_SINGLETON_POINTER(instance); }