C++版单例模式-现代化简洁写法

回顾一下单例模式,下面是现代最简洁的写法,且都保证了线程安全

饿汉式(线程安全)

程序启动时,实例就开始创建了,因此是线程安全的。

复制代码
class Singleton{
private:
    Singleton(){}
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
    static Singleton instance;//类内声明
public:
    static Singleton& getInstance(){
      return instance;
    }
}
Singleton Singleton::instance;

懒汉式(线程安全)

第一次调用instance函数时,实例才被创建出来,全局访问节点使用静态局部变量,保证了实例初始化一次且C++11规定静态局部变量是天然线程安全的

复制代码
class Singleton{
private:
  Singleton(){}
  Singleton(const Singleton&) = delete;
  Singleton& operator=(const Singleton&) = delete; 
public:
  Singleton& getInstance(){
      static Singleton instance;
      return instance;
  }
}
相关推荐
clint4562 天前
C++进阶(1)——前景提要
c++
夜悊3 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴3 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0013 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾3 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you3 天前
constexpr函数
c++
凡人叶枫3 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫3 天前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss3 天前
BRpc使用
c++·rpc
-森屿安年-3 天前
63. 不同路径 II
c++·算法·动态规划