新闻资讯

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

< 返回新闻资讯列表

c++单例模式的实现有什么方法,单例模式c++11

发布时间:2024-01-05 01:39:35

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;
  1. 懒汉式单例模式:在第一次使用时才创建单例对象。这类方法的缺点是需要使用额外的线程同步机制来保证多线程环境下的安全性。
class Singleton {
private:
    static Singleton* instance;
    Singleton() {}

public:
    static Singleton* getInstance() {
        if (instance == nullptr) {
            instance = new Singleton();
        }
        return instance;
    }
};

Singleton* Singleton::instance = nullptr;
  1. 两重检查锁单例模式:在懒汉式单例模式的基础上加入了两重检查,在多线程环境下保证安全性并减少锁的使用次数。
class Singleton {
private:
    static Singleton* instance;
    static std::mutex mtx;
    Singleton() {}

public:
    static Singleton* getInstance() {
        if (instance == nullptr) {
            std::lock_guard<std::mutex> lock(mtx);
            if (instance == nullptr) {
                instance = new Singleton();
            }
        }
        return instance;
    }
};

Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mtx;
  1. 静态局部变量单例模式:利用C++的静态局部变量特性,在需要时创建单例对象,并确保多线程安全。
class Singleton {
private:
    Singleton() {}

public:
    static Singleton* getInstance() {
        static Singleton instance;
        return &instance;
    }
};