C++ 单例模式 模板类的小问题

C++ 单例模式 模板类的小问题

介绍:添加一个C++单例模式的小知识。

单例模式的知识

  1. 单例模式实现分为饿汉式和懒汉式。
  2. 单例模式需要实现线程安全。
  3. 单例模式所拥有的对象需要在程序退出时销毁。
  4. 单例模式需要私有化构造函数、借助静态成员实现。
  5. 本文重点:对于单例模板的使用一定要显示具体化声明,不然会导致生成多个模板实例,生成多个单例对象。

饿汉式

饿汉式天生是线程安全的,所以不需要借助 call_once 现线程安全。通过智能指针来自动调用析构函数。

cpp 复制代码
/*
 * 单例饿汉模式: 天生就是线程安全的, 内存分配在heap,返回的是指针
 * 但是不能保证对T本身操作是线程安全的!
 * 如果需要保证T的操纵也是线程安全的需要T自己实现线程安全
 * */
template<typename T>
class singleton_hungry_heap {
public:
    static T* get_ptr(){
        return singleton_hungry_heap::instance_.get();
    }

    static T& get_reference(){
        return *(singleton_hungry_heap::instance_.get());
    }
private:
    singleton_hungry_heap() = default;
    singleton_hungry_heap(const singleton_hungry_heap&) = default;
    singleton_hungry_heap& operator=(const singleton_hungry_heap&) = default;
    ~singleton_hungry_heap()= default;
private:
    static std::unique_ptr<T> instance_ ;
};
template<typename T>
std::unique_ptr<T> singleton_hungry_heap<T>::instance_ = std::unique_ptr<T>(new T());

懒汉式

需要借助 call_once 现线程安全。

cpp 复制代码
/*
 * 单例懒汉模式: 实现线程安全、利用pthread_once实现
 * 但是不能保证对T本身操作是线程安全的!
 * 如果需要保证T的操纵也是线程安全的需要T自己实现线程安全
 * */
template<typename T>
class singleton_lazy_heap{
private:
    singleton_lazy_heap() = default;
    singleton_lazy_heap(const singleton_lazy_heap&) = default;
    singleton_lazy_heap& operator=(const singleton_lazy_heap&) = default;
    ~singleton_lazy_heap()= default;
public:
    static T* get_ptr(){
        std::call_once(singleton_lazy_heap<T>::_flag, singleton_lazy_heap<T>::init);
        return instance_.get();
    }

    static T& get_reference(){
        std::call_once(singleton_lazy_heap<T>::_flag, singleton_lazy_heap<T>::init);
        return *(instance_.get());
    }
private:
    static void init(){
        singleton_lazy_heap::instance_ = std::unique_ptr<T>(new T());
    }

    static std::once_flag _flag;

    static  std::unique_ptr<T> instance_;
};

template<typename T>
std::once_flag singleton_lazy_heap<T>::_flag = std::once_flag();

template<typename T>
std::unique_ptr<T> singleton_lazy_heap<T>::instance_ = nullptr;

为什么要显示实例化

首先建一个 Person类,然后创建一个单例类 singleton_lazy_heap<Person>,为了方便声明定义都放在person.hpp中。

cpp 复制代码
struct Person{
private:
    int age{0};
public:
    explicit Person(): age(0){
        fmt::print("Person create!\n");
    }

    explicit Person(const int& _age): age(_age){}

    [[nodiscard]] int get_age() const{
        return age;
    }

    void set_age(const int& _age){
        this->age = _age;
    }

    ~Person(){
        fmt::print("Person destructor!\n");
    }
};

接下来我们定义另一个类 King,声明在 king.hpp,定义在king.cpp中。

cpp 复制代码
#include "singleton.hpp"
#include "person.hpp"

struct King {
public:
    int get_person_age();
};

定义内容:

cpp 复制代码
#include "king.hpp"

int King::get_person_age() {
   //返回Person单例的age
    return singleton_lazy_heap<Person>::get_ptr()->get_age();
}

然后我们在main.cpp中使用 King.hpp

cpp 复制代码
#include "singleton.hpp"
#include "person.hpp"
#include "king.hpp"

int main() {
    singleton_lazy_heap<Person>::get_ptr()->set_age(10);
    //内存中应该只有一个Person对象 age的值是10
    King k;
    //实际返回时 0
    std::cout << k.get_person_age() << std::endl; //0
}

你以为会返回10,结果返回的是0。然后调试查看返回的内存地址,你会发现结果生成了两个Person对象。

原因 :不同编译单元cpp文件中的 singleton_lazy_heap<Person>::get_ptr() 返回不同的指针,不同的编译单元中多次实例化该模板,导致每个实例都会有自己独立的状态,这样单例模式不就失效了吗?仅仅在一个cpp文件中是多线程安全进一个对象?这那叫什么单例模式!

解决方法 :不要使用隐式实例化 ,使用显示实例化。我们在Person文件中添加一行即可。

cpp 复制代码
struct Person{
private:
    int age{0};
public:
    explicit Person(): age(0){
        fmt::print("Person create!\n");
    }

    explicit Person(const int& _age): age(_age){}

    [[nodiscard]] int get_age() const{
        return age;
    }

    void set_age(const int& _age){
        this->age = _age;
    }

    ~Person(){
        fmt::print("Person destructor!\n");
    }
};

template class singleton_lazy_heap<Person>;

然后就正常了,返回10;

总结:单例模板类,一定要使用具体实例化,不然,跨文件使用单例对象时,不同的编译单元中会多次实例化模板,导致每个实例都会有自己独立的状态生成多个所谓的单例。

相关推荐
招摇的一半月亮1 小时前
P2242 公路维修问题
数据结构·c++·算法
f***01932 小时前
CC++链接数据库(MySQL)超级详细指南
c语言·数据库·c++
合方圆~小文2 小时前
球型摄像机作为现代监控系统的核心设备
java·数据库·c++·人工智能
椰萝Yerosius3 小时前
[题解]2024CCPC郑州站——Z-order Curve
c++·算法
滨HI06 小时前
C++ opencv简化轮廓
开发语言·c++·opencv
学习路上_write6 小时前
FREERTOS_互斥量_创建和使用
c语言·开发语言·c++·stm32·单片机·嵌入式硬件
闻缺陷则喜何志丹8 小时前
【SOSDP模板 容斥原理 逆向思考】3757. 有效子序列的数量|分数未知
c++·算法·力扣·容斥原理·sosdp·逆向思考
BestOrNothing_20158 小时前
一篇搞懂 C++ 重载:函数重载 + 运算符重载,从入门到会用(含 ++、<<、== 实战)
c++·函数重载·运算符重载·operator·前置后置++·重载与重写
2501_941144428 小时前
Python + C++ 异构微服务设计与优化
c++·python·微服务
程序猿编码8 小时前
PRINCE算法的密码生成器:原理与设计思路(C/C++代码实现)
c语言·网络·c++·算法·安全·prince