C++单例模式

简单懒汉模式:

Foo.h

#ifndef FOO_H
#define FOO_H

class Foo
{
public:
    static Foo* getInstance();
    ~Foo();

private:
    Foo();
    static Foo* instance;

};
#endif

Foo.cpp

#include "Foo.h"
#include <mutex>
std::mutex fooMutex; Foo
* Foo::instance = NULL; Foo::Foo() { } Foo* Foo::getInstance() { fooMutex.lock(); if (NULL == instance) { instance = new Foo(); } fooMutex.unlock(); return instance; } Foo::~Foo() { if (NULL != instance) { delete instance; instance = NULL; } }

 

posted @ 2019-03-12 10:24  代萌  阅读(143)  评论(0编辑  收藏  举报