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