修正《深入应用C++11代码优化与工程级应用》代码错误

s在8.5改进对象池一节中展示的代码有误:

1.作者为了实现在对象池被销毁后将从里面取出的对象用完后能被自动销毁而不是继续存入已经销毁的对象池中,为对象池加了一个needClear属性,同时将每个取出的对象用shared_ptr封装,并设计特别的删除器,该删除器捕获了this指针,这个操作会在this被销毁后失效,从而出现野指针

2.对象池应该为单例模式,不应该被多次创建

修改代码如下:

工具类:

class noncopyable{
protected:
    noncopyable()= default;
public:
    noncopyable(const noncopyable&)=delete;
    noncopyable& operator=(const noncopyable&) = delete;
};

单例工厂:

#include <utility>
#include "type_traits"
#include "exception"
template<class T>
class singleton{
public:
    using source_type = typename std::decay<T>::type;
    template<class ... Args>
    static source_type& get_instance(Args&& ... args){
        if(!m_ptr) {
            m_ptr = new source_type(std::forward<Args>(args)...);
        }
        return *m_ptr;
    }
    static void destroy(){
        delete m_ptr;
        m_ptr = nullptr;
    }
    static bool exist(){
        return m_ptr!=nullptr;
    }
    static source_type& instance() noexcept(false){
        if(!m_ptr) {
            throw std::logic_error("instance didn't exit");
        }
        return *m_ptr;
    }
    singleton() = delete;
    ~singleton() = delete;
    singleton(const singleton<source_type>&) = delete;
    singleton<source_type>&operator =(const singleton<source_type>&) = delete;
private:
    static source_type* m_ptr;
};
template<class c>
typename singleton<c>::source_type * singleton<c>::m_ptr = nullptr;

对象池:

//
// Created by lyz31 on 2023/10/12.
//

#ifndef TOOL_OBJECT_POOL_H
#define TOOL_OBJECT_POOL_H
#include "map"
#include "memory"
#include "functional"
#include "singleton.h"
#include "noncopyable.h"
template<typename T>
class object_pool:private noncopyable{
private:
    friend singleton<object_pool>;//表示允许单例工厂管理自己
    std::multimap<std::string,std::shared_ptr<T>> source;
    template<typename ...Argus>
    using constructor = std::function<std::shared_ptr<T>(Argus...)>;
    template<typename ... Argus>
    std::string get_key(){
        return typeid(constructor<Argus...>).name();
    };
    std::shared_ptr<T> process(std::string key,std::shared_ptr<T>& t){
        auto del = [&key](T *t){
            if(singleton<object_pool<T>>::exist()){
                singleton<object_pool<T>>::instance().add_object(key,t);//这个就是默认构造函数
            }else{
                delete t;
            }
        };
        std::shared_ptr<T> res(nullptr,del);
        res.swap(t);//交换控制权
        return res;
    }

    explicit object_pool() = default;
    virtual ~object_pool()= default; //允许继承
public:
    template<typename ... Argus>
    void init(size_t s,Argus ...argus){
        auto key = get_key<Argus...>();
        source.clear();
        for (int i = 0; i < s; ++i) {
            source.emplace(key,std::make_shared<T>(argus...));
        }
    }

    template<typename ...Argus>
    std::shared_ptr<T> get(){
        auto range = source.equal_range(get_key<Argus...>());
        if (range.first==range.second) return nullptr;
        auto key = range.first->first;
        auto res= process(key,range.first->second);
        source.erase(range.first);
        return res;
    }

    void add_object(const std::string&  key,T* t){
        source.emplace(key,t);
    }
    size_t size(){
        return source.size();
    }

};


#endif //TOOL_OBJECT_POOL_H

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
深入应用C语言代码优化工程应用》是一本很有指导意义的书籍,对于想要深入学习C语言的人来说是一本很好的参考书。本书主要涵盖了C语言代码优化技术和工程应用,对于提高代码效率和开发质量都有很大的帮助。 首先,本书介绍了一些常见的代码优化技术,如循环展开、循环合并、循环变换等。这些技术可以帮助程序员在编写代码时更加高效地利用计算机资源,提高程序运行的速度和效率。例如,通过循环展开可以避免循环每次都判断循环条件,从而减少了循环的开销。 其次,本书还介绍了一些常用的工程应用方法,如模块化编程、错误处理等。这些方法可以帮助程序员在大型项目开发中更加规范地组织代码,提高代码的可读性和可维护性。例如,通过模块化编程可以将功能相似的代码封装成独立的模块,便于重复利用和维护。 此外,本书还介绍了一些与C语言开发相关的工具和技术,如调试和性能分析工具、代码版本管理工具等。这些工具和技术可以帮助程序员更加方便地进行代码开发和维护,提高开发效率和质量。 总之,《深入应用C语言代码优化工程应用》是一本很好的书籍,深入讲解了C语言代码优化工程应用的相关知识和技术。读完这本书,读者可以更好地理解C语言代码的运行原理和优化方法,提高自己在C语言开发中的技术水平和工作效率。无论是初学者还是有一定编程经验的人都可以从本书中获益匪浅。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值