C++中单例的多种写法

2024-12-30 19:37:37   小编

C++中单例的多种写法

在 C++编程中,单例模式是一种常见且实用的设计模式。单例模式确保一个类只有一个实例存在,并提供全局访问点。下面我们来探讨几种常见的 C++中单例的写法。

懒汉式单例

懒汉式单例在第一次被调用时才创建实例。

class LazySingleton {
private:
    static LazySingleton* instance;
    LazySingleton() {}

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

LazySingleton* LazySingleton::instance = nullptr;

饿汉式单例

饿汉式单例在程序启动时就创建实例。

class HungrySingleton {
private:
    static HungrySingleton instance;

    HungrySingleton() {}

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

HungrySingleton HungrySingleton::instance;

双重检查锁单例

这是一种优化的懒汉式单例,通过双重检查锁来提高性能。

class DoubleCheckSingleton {
private:
    static DoubleCheckSingleton* instance;
    static std::mutex mtx;

    DoubleCheckSingleton() {}

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

DoubleCheckSingleton* DoubleCheckSingleton::instance = nullptr;
std::mutex DoubleCheckSingleton::mtx;

静态局部变量单例

利用 C++中局部静态变量的特性实现单例。

class StaticLocalSingleton {
private:
    StaticLocalSingleton() {}

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

不同的单例写法在不同的场景下各有优劣。懒汉式单例延迟创建实例,节省资源,但在多线程环境下可能存在问题;饿汉式单例简单直接,但可能在程序启动时就消耗不必要的资源;双重检查锁单例在多线程环境下性能较好,但代码相对复杂;静态局部变量单例写法简洁,线程安全。

在实际编程中,根据具体的需求和项目特点,选择合适的单例写法,能够有效地管理资源和提高程序的可维护性。

TAGS: C++单例模式 C++单例写法 单例模式C++ C++编程单例

欢迎使用万千站长工具!

Welcome to www.zzTool.com