众所周知,单例模式分为两种,1)懒汉模式 2)饿汉模式
下面的两种实现均线程安全
1、通过call_once包装的懒汉模式(建议使用)
#include <mutex>
class Singleton
{
public:
static Singleton* getInstance(){
std::call_once(initInstanceFlag, [&](){ instance = new Singleton(); });
return instance;
}
private:
Singleton() = default;
~Singleton() = default;
Singleton(const Singleton &) = delete;
Singleton &operator=(const Singleton &) = delete;
static Singleton *instance;
static std::once_flag initInstanceFlag;
};
Singleton *Singleton::instance = nullptr;
std::once_flag Singleton::initInstanceFlag;
2.饿汉模式 (缺点是:会占用程序启动的时间,不太符合即用即定义)
class Singleton {
public:
static Singleton* getInstance() {
return instance;
}
private:
static Singleton* instance;
Singleton() = default;
~Singleton() = default;
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
};
Singleton* Singleton::instance = new Singleton();