class Singleton
{
private: Singleton(){}
public:
static Singleton s1;
static Singleton* GetInstance()
{
return &s1;
}
Singleton(const Singleton&) = delete;
Singleton& operator= (const Singleton &) = delete;
};
int main()
{
Singleton* p = Singleton::GetInstance();
return 0;
}//为调用主函数前就已经创建了该对象,单例模式多用于日志模块或者数据库模块,饿汉式是线程安全的。
std::mutex mx;
class Singleton
{
private: Singleton() {}
public:
static Singleton* volatile s1;
static Singleton* GetInstance()
{
if (s1 == nullptr)
{
std::lock_guard<std::mutex>lock(mx); //锁+双重判断 线程安全的懒汉式单例模式最安全的
if(s1 == nullptr)
s1 = new Singleton();
}
return s1;
}
Singleton(const Singleton&) = delete;
Singleton& operator= (const Singleton&) = delete;
};
Singleton* volatile Singleton::s1 = nullptr; //CPU为了提高效率会进行该内容的拷贝给每个线程,加上这个之后将不会再进行拷贝而使每个线程可以察觉到
//非常精简的懒汉单例模式,静态成员局部变量本身就是线程安全的问题。
class Singleton
{
private: Singleton() {}
public:
static Singleton* GetInstance()
{
static Singleton s1;
return &s1;
}
Singleton(const Singleton&) = delete;
Singleton& operator= (const Singleton&) = delete;
};