C++ 单例模式

1.饿汉式

使用饿汉模式实现单例是十分简单的,并且有效避免了线程安全问题,因为将该单例对象定义为static变量,程序启动即将其构造完成了。代码实现:

#include <iostream>

class Singleton {
public:
    // 获取单例实例的静态函数
    static Singleton* GetInstance() {
        return singleton_;
    }

    // 销毁单例实例的静态函数
    static void DestroyInstance() {
        if (singleton_ != nullptr) {
            delete singleton_;
            singleton_ = nullptr; // 置空指针,防止悬挂指针
        }
    }

private:
    // 防止外部构造实例。
    Singleton() = default;

    // 防止拷贝和赋值构造,将其声明为删除函数,确保不可用。
    Singleton& operator=(const Singleton&) = delete;
    Singleton(const Singleton& singleton2) = delete;

private:
    static Singleton* singleton_; // 单例实例的指针
};

// 类外初始化静态成员变量为单例实例
Singleton* Singleton::singleton_ = new Singleton;

int main() {
    // 函数内获取实例
    Singleton* s1 = Singleton::GetInstance(); // 获取单例实例
    std::cout << "s1 的地址:" << s1 << std::endl;

    Singleton* s2 = Singleton::GetInstance(); // 再次获取单例实例,应与 s1 相同
    std::cout << "s2 的地址:" << s2 << std::endl;

    Singleton::DestroyInstance(); // 销毁单例实例

    return 0;
}

2.懒汉式

饿汉方式不论是否需要使用该对象都将其定义出来,可能浪费了内存,或者减慢了程序的启动速度。所以使用懒汉模式进行优化,懒汉模式即延迟构造对象,在第一次使用该对象的时候才进行new该对象。

  而懒汉模式会存在线程安全问题,最出名的解决方案就是Double-Checked Locking Pattern (DCLP)双重检查锁。使用两次判断来解决线程安全问题并且提高效率。代码实现:

#include <iostream>
#include <mutex>

class Singleton {
public:
    // 获取单例实例的静态函数
    static Singleton* GetInstance() {
        if (instance_ == nullptr) {
            std::lock_guard<std::mutex> lock(mutex_); // 使用互斥锁确保线程安全
            if (instance_ == nullptr) {
                instance_ = new Singleton; // 创建单例实例
            }
        }
        return instance_;
    }

    // 析构函数,默认析构即可,无需手动删除实例。
    ~Singleton() = default;

    // 销毁单例实例的函数
    void Destroy() {
        if (instance_ != nullptr) {
            delete instance_; // 删除实例
            instance_ = nullptr; // 置空指针,防止悬挂指针
        }
    }

    // 打印单例实例的地址
    void PrintAddress() const {
        std::cout << this << std::endl;
    }

private:
    // 防止外部构造实例。
    Singleton() = default;

    // 防止拷贝和赋值构造,将其声明为删除函数,确保不可用。
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

private:
    static Singleton* instance_; // 单例实例的指针
    static std::mutex mutex_; // 互斥锁,用于线程安全的单例创建
};

Singleton* Singleton::instance_ = nullptr; // 初始化静态成员变量为nullptr
std::mutex Singleton::mutex_; // 初始化静态成员变量为互斥锁

int main() {
    Singleton* s1 = Singleton::GetInstance(); // 获取单例实例
    std::cout << "s1 的地址:";
    s1->PrintAddress(); // 打印实例地址

    Singleton* s2 = Singleton::GetInstance(); // 再次获取单例实例,应与 s1 相同
    std::cout << "s2 的地址:";
    s2->PrintAddress(); // 打印实例地址

    // 注意:不需要手动销毁单例实例,由析构函数自动处理

    return 0;
}

3.懒汉式优化

上述代码有一个问题,当程序使用完该单例,需要手动去调用Destroy()来释放该单例管理的资源。如果不去手动释放管理的资源(例如加载的文件句柄等),虽然程序结束会释放这个单例对象的内存,但是并没有调用其析构函数去关闭这些管理的资源句柄等。解决办法就是将该管理的对象用智能指针管理。代码如下:

#include <iostream>
#include <memory>
#include <mutex>

class Singleton {
public:
    // 获取单例实例的静态函数,返回引用
    static Singleton& GetInstance() {
        if (!instance_) {
            std::lock_guard<std::mutex> lock(mutex_); // 使用互斥锁确保线程安全
            if (!instance_) {
                instance_.reset(new Singleton); // 创建单例实例的智能指针
            }
        }
        return *instance_; // 返回单例实例的引用
    }

    // 析构函数,默认析构即可,无需手动删除实例。
    ~Singleton() = default;

    // 打印单例实例的地址
    void PrintAddress() const {
        std::cout << this << std::endl;
    }

private:
    // 防止外部构造实例。
    Singleton() = default;

    // 防止拷贝和赋值构造,将其声明为删除函数,确保不可用。
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

private:
    static std::unique_ptr<Singleton> instance_; // 单例实例的智能指针
    static std::mutex mutex_; // 互斥锁,用于线程安全的单例创建
};

std::unique_ptr<Singleton> Singleton::instance_; // 初始化静态成员变量为 nullptr
std::mutex Singleton::mutex_; // 初始化静态成员变量为互斥锁

int main() {
    Singleton& s1 = Singleton::GetInstance(); // 获取单例实例的引用
    std::cout << "s1 的地址:";
    s1.PrintAddress(); // 打印实例地址

    Singleton& s2 = Singleton::GetInstance(); // 再次获取单例实例,应与 s1 相同
    std::cout << "s2 的地址:";
    s2.PrintAddress(); // 打印实例地址

    // 注意:不需要手动销毁单例实例,由析构函数自动处理

    return 0;
}

4.线程安全问题

if (instance_ == nullptr) { \\ 语句1
  std::lock_guard<std::mutex> lock(mutex_);
  if (instance_ == nullptr) {
    instance_ = new Singleton; \\ 语句2
  }
}

线程安全问题产生的原因是多个线程同时读或写同一个变量时,会产生问题。
如上代码,对于语句2是一个写操作,我们用mutex来保护instance_这个变量。但是语句1是一个读操作,if (instance_ == nullptr),这个语句是用来读取instance_这个变量,而这个读操作是没有锁的。所以在多线程情况下,这种写法明显存在线程安全问题。
《C++ and the Perils of Double-Checked Locking》这篇文章中提到:

instance_ = new Singleton;

这条语句实际上做了三件事,第一件事申请一块内存,第二件事调用构造函数,第三件是将该内存地址赋给instance_。

1申请内存

2调用构造

3赋值地址

132 则对于b判断 ins 不为空,直接构造,出问题

但是不同的编译器表现是不一样的。可能先将该内存地址赋给instance_,然后再调用构造函数。这是线程A恰好申请完成内存,并且将内存地址赋给instance_,但是还没调用构造函数的时候。线程B执行到语句1,判断instance_此时不为空,则返回该变量,然后调用该对象的函数,但是该对象还没有进行构造。

5.局部静态变量

  1. 延迟初始化: 局部静态变量只有在第一次访问该函数时才会被初始化。这意味着单例对象只有在需要的时候才会被创建,而不是在程序启动时就创建,从而减小了初始化开销。

  2. 线程安全: C++11规定,在多线程环境下,局部静态变量的初始化是线程安全的。这意味着多个线程可以同时访问 GetInstance 函数,而不会导致竞态条件或资源冲突。

#include <iostream>

class Singleton {
public:
    // 获取单例实例的静态函数,返回引用
    static Singleton& GetInstance() {
        static Singleton instance; // 使用局部静态变量,确保线程安全的单例创建
        return instance; // 返回单例实例的引用
    }

    // 析构函数,默认析构即可,无需手动删除实例。
    ~Singleton() = default;

private:
    // 防止外部构造实例。
    Singleton() = default;

    // 防止拷贝和赋值构造,将其声明为删除函数,确保不可用。
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
};

int main() {
    Singleton& s1 = Singleton::GetInstance(); // 获取单例实例的引用
    std::cout << "s1 的地址:" << &s1 << std::endl;

    Singleton& s2 = Singleton::GetInstance(); // 再次获取单例实例,应与 s1 相同
    std::cout << "s2 的地址:" << &s2 << std::endl;

    // 注意:不需要手动销毁单例实例,由析构函数自动处理

    return 0;
}

#include<iostream>
using namespace std;

class Singleton {

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

	// 实现一个打印实例地址的函数
	void print_s() {
		cout << "地址为" << this << endl;
	}
private:
	Singleton() = default;
	Singleton(const Singleton& s) = delete;
	Singleton& operator=(const Singleton&) = delete;

};


int main() {

	Singleton& s1 = Singleton::GetInstance();
	s1.print_s();
}

### 单例模式的基本概念 单例模式是创建型设计模式的一种,其核心思想是确保一个类仅有一个实例,并提供一个全局访问点来获取这个实例。在程序运行期间,单例模式可以保证一个类只有一个实例对象,并提供全局访问接口[^1][^2][^4]。 ### 实现方法 #### 饿汉饿汉式在程序开始时就创建实例,线程安全,但可能会造成资源浪费。 ```cpp #include <iostream> class Singleton { public: static Singleton& getInstance() { return instance; } void showMessage() { std::cout << "Hello from Singleton!" << std::endl; } private: Singleton() { std::cout << "Singleton Constructor Called" << std::endl; } // 防止复制 Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; static Singleton instance; }; Singleton Singleton::instance; int main() { Singleton& instance1 = Singleton::getInstance(); Singleton& instance2 = Singleton::getInstance(); instance1.showMessage(); if (&instance1 == &instance2) { std::cout << "Both instances are the same." << std::endl; } return 0; } ``` #### 懒汉式(非线程安全) 懒汉式在第一次使用时才创建实例,但非线程安全。 ```cpp #include <iostream> class Singleton { public: static Singleton* getInstance() { if (instance == nullptr) { instance = new Singleton(); } return instance; } void showMessage() { std::cout << "Hello from Singleton!" << std::endl; } private: Singleton() { std::cout << "Singleton Constructor Called" << std::endl; } // 防止复制 Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; static Singleton* instance; }; Singleton* Singleton::instance = nullptr; int main() { Singleton* instance1 = Singleton::getInstance(); Singleton* instance2 = Singleton::getInstance(); instance1->showMessage(); if (instance1 == instance2) { std::cout << "Both instances are the same." << std::endl; } return 0; } ``` #### 懒汉式(线程安全) 使用互斥锁保证线程安全,但会有一定的性能开销。 ```cpp #include <iostream> #include <mutex> class Singleton { public: static Singleton& getInstance() { std::lock_guard<std::mutex> lock(mutex); if (instance == nullptr) { instance = new Singleton(); } return *instance; } void showMessage() { std::cout << "Hello from Singleton!" << std::endl; } private: Singleton() { std::cout << "Singleton Constructor Called" << std::endl; } // 防止复制 Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; static Singleton* instance; static std::mutex mutex; }; Singleton* Singleton::instance = nullptr; std::mutex Singleton::mutex; int main() { Singleton& instance1 = Singleton::getInstance(); Singleton& instance2 = Singleton::getInstance(); instance1.showMessage(); if (&instance1 == &instance2) { std::cout << "Both instances are the same." << std::endl; } return 0; } ``` #### 基于局部静态变量(C++11及以上) 简洁、安全且高效,推荐使用。 ```cpp #include <iostream> class Singleton { public: static Singleton& getInstance() { static Singleton instance; return instance; } void showMessage() { std::cout << "Hello from Singleton!" << std::endl; } // 防止复制 Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; private: Singleton() { std::cout << "Singleton Constructor Called" << std::endl; } }; int main() { Singleton& instance1 = Singleton::getInstance(); Singleton& instance2 = Singleton::getInstance(); instance1.showMessage(); if (&instance1 == &instance2) { std::cout << "Both instances are the same." << std::endl; } return 0; } ``` ### 使用场景 - **资源管理**:例如数据库连接池、文件系统操作等,避免多个实例同时操作同一资源导致冲突。 - **配置信息**:如全局的配置文件管理,确保所有模块使用相同的配置信息。 - **日志记录**:保证所有日志信息都记录到同一个日志文件中。 ### 注意事项 - **线程安全**:在多线程环境下,需要确保单例的创建和访问是线程安全的,可采用互斥锁或局部静态变量的方式。 - **生命周期管理**:确保单例对象在整个程序生命周期内的正确性,避免内存泄漏。 - **可测试性**:单例模式可能会影响代码的可测试性,可考虑使用依赖注入等技术来提高可测试性。 - **避免滥用**:单例模式会引入全局状态,过度使用可能导致代码耦合度增加,难以维护和扩展。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值