C++如何实现一个单例模式

3 分钟阅读 339 字 + 332 词
参考答案
在C++中实现单例模式,主要是确保一个类只有一个实例,并提供一个全局访问点, C++实现单例模式需要满足以下几点要求:
  • 私有化构造函数 :将类的构造函数定义为私有,防止外部通过 new 关键字创建多个实例。
  • 静态实例 :在类内部提供一个静态私有实例,这个实例将作为整个程序的唯一实例。
  • 静态公有访问方法 :提供一个公有的 静态 方法,通常称为 getInstance ,用于获取类的唯一实例。
  • 删除拷贝构造函数和赋值操作符 :为了防止通过拷贝或赋值来创建新的实例,需要将拷贝构造函数和赋值操作符定义为私有或删除。
单例模式有懒汉式和饿汉式两种实现。
  • 懒汉式 类实例只有在第一次被使用时才会创建,这个时候需要注意多线程下的访问,需要利用互斥锁来加以控制。
  • 饿汉式 类实例在类被加载时就进行创建。
//c++11 :方法一
class mySingleton
{
public:
    static mySingleton &getInstance()
    {
        static mySingleton inst;
        return inst;
    }
    ~mySingleton()
    {
    }
    mySingleton(const mySingleton &) = delete;
    mySingleton &operator=(const mySingleton &) = delete;

    //成员函数
private:
    mySingleton()
    {
    }

private:
    //成员
};

//利用模板加call_once生成单例模板,记得加友元
template <typename T>
class Singleton
{
public:
    static shared_ptr<T> getInstance()
    {
        static once_flag on;
        call_once(on, [&]()
                  { m_instance = shared_ptr<T>(new T()); });
        return m_instance;
    }
    Singleton(const Singleton<T> &) = delete;
    Singleton &operator=(const Singleton<T> &) = delete;
    ~Singleton() {};

protected:
    Singleton() {};

private:
    static shared_ptr<T> m_instance;
};
template <typename T>
shared_ptr<T> Singleton<T>::m_instance = nullptr;

class CartMgr : public Singleton<CartMgr>
{
public:
    friend class Singleton<CartMgr>;

    // 添加商品到购物车
    void add(const string &itemName, int quantity)
    {
        cart[itemName] += quantity;
    }

    // 查看购物车
    void print() const
    {
        for (const auto &item : cart)
        {
            cout << item.first << " " << item.second << endl;
        }
    }

private:
    CartMgr() = default;
    // 购物车存储商品和数量的映射
    map<string, int> cart;
};