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;

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

相关推荐
QiLinkOS2 小时前
【从实验室到商业战场:发明专利如何重塑科技与企业的共生生态】
大数据·c语言·数据结构·c++·人工智能·单片机·算法
Irissgwe2 小时前
c++11(lambda表达式与包装器、线程库)
c++·c++11·lambda表达式·线程库·包装器·互斥量库·条件变量库
Peter·Pan爱编程3 小时前
14. Lambda 表达式:随手可写的函数对象
c++·算法·ai编程
不想写代码的星星3 小时前
从分支预测角度看 C++:为什么你的热循环慢得离谱?
c++
郝学胜-神的一滴4 小时前
Qt 高级开发 018:复刻经典登录界面布局与窗口美化全解析
开发语言·c++·qt·程序人生·用户界面
郝亚军4 小时前
IEEE 754 单精度浮点的SEM表示
开发语言·c++·算法
Yyyyyy~5 小时前
【C++】数组篇
开发语言·c++
qq_333120975 小时前
C++高并发内存池的整体设计和实现思路_C 语言
java·c语言·c++
牛肉在哪里5 小时前
ros2 从零开始27 编写广播C++
开发语言·c++·机器人
Curvatureflight6 小时前
前端国际化 i18n 落地实践:语言包、动态文案和格式化问题怎么处理?
前端·c++·vue