单例模式确保一个类的实例话只能有一个对象,单例模式在日志系统,数据库操作中比较常见。常见的饿汉模式和懒汉模式不在过多介绍,以下是C++11实现单例的方式,一种是使用static确保只有一个实例,一种是利用call_once确保只执行一次初始化。
#include <iostream>
#include <mutex>
class Singleton
{
public:
static Singleton& GetInstance()
{
static Singleton instance;
return instance;
}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
private:
Singleton() = default;
};
class Singleton
{
public:
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static Singleton* GetInstance()
{
std::call_once(m_flg, [&]()
{
m_instance = new Singleton;
});
return m_instance;
}//使用call_once确保只会执行一次,也就是只会执行一次m_instance = new Singleton;
private:
Singleton() = default;
static std::once_flag m_flg;
static Singleton* m_instance ;
};
std::once_flag Singleton::m_flg;
Singleton* Singleton::m_instance = nullptr; //类中定义的static需要在类外初始化