Skip to content

单例模式 ​

cpp
#include<iostream>
#include<mutex>
#include<atomic>
#include<thread>
#include<vector>
#include<memory>
// 单例模式:保证一个类全局只有一个实例,并提供统一的访问点

class SingletonMeyers
{
public:
    // 获取单例对象
    static SingletonMeyers& getInstance()
    {
        static SingletonMeyers instance;   // 函数内 static 局部变量
        return instance;
    }

    SingletonMeyers(const SingletonMeyers&) = delete;
    SingletonMeyers& operator=(const SingletonMeyers&) = delete;

private:
    // 构造函数私有化,防止外部创建对象
    SingletonMeyers() {}  
};