1. 程式人生 > >C++ 宏定義創建(銷毀)單例

C++ 宏定義創建(銷毀)單例

let creat span singleton () tor inter col unlock

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);
}

C++ 宏定義創建(銷毀)單例