- 饿汉模式: 类加载的时候就已经实例化,并且创建单例对象,以后只管用即可。 天然多线程安全, 不需要时,也要占用资源(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;
}
};
- 懒汉模式: 需要时再加载,存在多线程安全问题, 最简单实现:
#include <iostream>
#include <memory>
#include <mutex>
class signleton{
private:
signleton(){ std::cout << "Sigleton construct" << std::endl;}
signleton (const signleton&) = delete;
signleton& operator=(const signleton&) = delete;
public:
static std::unique_ptr<signleton> _ptr;
static signleton& getInstance()
{
static std::once_flag flag;
std::cout << "getInstance" << std::endl;
std::call_once(flag, [&](){_ptr.reset(new signleton);});
return *_ptr;
}
};
std::unique_ptr<signleton> signleton::_ptr;
int main(){
std::cout << "sigletonbaseonlazy" << std::endl;
signleton& s1 = signleton::getInstance();
signleton& s2 = signleton::getInstance();
return 0;
}