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;

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

相关推荐
小飞猪Jay2 小时前
C++面试速通宝典——13
jvm·c++·面试
rjszcb3 小时前
一文说完c++全部基础知识,IO流(二)
c++
小字节,大梦想3 小时前
【C++】二叉搜索树
数据结构·c++
吾名招财3 小时前
yolov5-7.0模型DNN加载函数及参数详解(重要)
c++·人工智能·yolo·dnn
我是哈哈hh4 小时前
专题十_穷举vs暴搜vs深搜vs回溯vs剪枝_二叉树的深度优先搜索_算法专题详细总结
服务器·数据结构·c++·算法·机器学习·深度优先·剪枝
憧憬成为原神糕手4 小时前
c++_ 多态
开发语言·c++
郭二哈4 小时前
C++——模板进阶、继承
java·服务器·c++
挥剑决浮云 -4 小时前
Linux 之 安装软件、GCC编译器、Linux 操作系统基础
linux·服务器·c语言·c++·经验分享·笔记
丶Darling.4 小时前
LeetCode Hot100 | Day1 | 二叉树:二叉树的直径
数据结构·c++·学习·算法·leetcode·二叉树
labuladuo5205 小时前
Codeforces Round 977 (Div. 2) C2 Adjust The Presentation (Hard Version)(思维,set)
数据结构·c++·算法