新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

c++怎么实现单例模式,c++单例模式的几种实现方式

发布时间:2023-10-21 13:04:08

c++怎样实现单例模式

在C++中,可以通过以下两种方式实现单例模式:

  1. 饿汉式单例模式:
class Singleton {
private:
    static Singleton* instance;
    Singleton() {} // 将构造函数设为私有,制止外部创建对象
public:
    static Singleton* getInstance() {
        if (instance == nullptr) {
            instance = new Singleton();
        }
        return instance;
    }
};

Singleton* Singleton::instance = nullptr;

使用时可以通过Singleton::getInstance()获得单例对象。

  1. 懒汉式单例模式:
class Singleton {
private:
    static Singleton* instance;
    Singleton() {} // 将构造函数设为私有,制止外部创建对象
public:
    static Singleton* getInstance() {
        if (instance == nullptr) {
            instance = new Singleton();
        }
        return instance;
    }
};

Singleton* Singleton::instance = nullptr;

使用时可以通过Singleton::getInstance()获得单例对象。

这两种方式都将构造函数设为私有,制止外部创建对象,通过静态成员变量和静态成员函数来实现单例对象的创建和获得。在饿汉式中,单例对象在程序启动时就会被创建出来,在懒汉式中,单例对象在第一次被使用时才会被创建出来。