- 饿汉模式: 类加载的时候就已经实例化,并且创建单例对象,以后只管用即可。 天然多线程安全, 不需要时,也要占用资源(static 不占内存)
class Sigleton{
private:
Sigleton(){ std::cout << “Sigleton construct” << std::endl;}
public:
Sigleton(const Sigleton&) = delete;
Sigleton& operator=(const Sigleton&) = delete;
static Sigleton& getInstance()
{
static Sigleton s;
return s;
}
};
- 懒汉模式: 需要时再加载,存在多线程安全问题, 最简单实现:
#define SINGLETON_CTOR(x)
private:
x() = default;
x(const x&)=delete;
x& operator=(const x&)=delete;
~x()=default;
class SingletonUsePtr2
{
SINGLETON_CTOR(SingletonUsePtr2);
public:
static SingletonUsePtr2& Instance()
{
static std::once_flag s_flag;
std::call_once(s_flag, & {
_ptr.reset(new SingletonUsePtr2);
});
return *_ptr;
}
private:
static std::unique_ptr _ptr;
};