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

 

posted @ 2019-03-14 14:22  代萌  阅读(284)  评论(0编辑  收藏  举报