有可能使用shared_ptr的对象池模式吗? [英] Is an Object Pool pattern of shared_ptr possible?

查看:83
本文介绍了有可能使用shared_ptr的对象池模式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建一个shared_ptr的对象池?在脑海中画出草图,我可以看到两种方法,但是每种方法都有缺陷:

Is it possible to create an Object Pool of shared_ptr? Sketching this in my head, I can see two ways of doing this but each have a flaw:

  1. 如果将T对象存储在可重用的池中,则在get()请求上将T包装在shared_ptr中的行为将导致控制块每次都在堆上重新分配-因此,打破了概念对象池.

  1. If T objects were stored in a reusable pool, the act of wrapping T in a shared_ptr on a get() request would result in the control block being re-allocated on the heap each time - therefore breaking the concept of an Object Pool.

如果将shared_ptr对象存储在可重用的池中,则shared_ptr对象必须停止存在才能启动自定义删除器,并且仅使用T指针调用自定义删除器函数.因此,没有什么可回收的.

If shared_ptr objects were stored in a reusable pool, the shared_ptr object must stop existing to initiate a custom deleter, and the custom deleter function only gets called with a T pointer. So there is nothing to recycle.

推荐答案

经过详尽的研究和测试,我得出的结论是,没有 合法的方式(从C ++ 11或更低版本开始)直接包含可重复使用的 shared_ptr< T> 的对象池.当然,可以很容易地为 shared_ptr< T> 提供服务的 T 对象池,但是会为控制块的每一次服务导致堆分配.

After exhaustive research and testing I have concluded that there is no legitimate way (as of C++11 or below) to make an object pool of reusable shared_ptr<T>'s directly. Certainly one can make a pool of T objects quite easily that serves shared_ptr<T>'s, but that results in heap allocation with every serve for the control block.

但是 可能是间接创建 shared_ptr< T> 的对象池的(这是我唯一的 方法发现做到了).间接地说,我的意思是必须实现一个自定义的内存池"样式分配器,以存储在 shared_ptr< T> 控制块被破坏时释放的内存,以供重新使用.然后将该分配器用作"shared_ptr"构造函数的第三个参数:

It is possible however to make an object pool of shared_ptr<T>'s indirectly (and this is the only way I have found to do it). By indirectly, I mean one must implement a custom 'memory pool' style allocator to store for reuse the memory released when shared_ptr<T> control blocks are destroyed. This allocator is then used as the third parameter of the `shared_ptr' constructor:

template< class Y, class Deleter, class Alloc > 
   std::shared_ptr( Y* ptr, Deleter d, Alloc alloc );

shared_ptr< T> 仍将使用堆内存来构造/分配和删除/取消分配-无法停止它-但是通过自定义分配器使内存可重复使用,确定性的内存占用量可以实现.

The shared_ptr<T> will still be constructed/allocated and deleted/de-allocated with heap memory - there is no way to stop it - but by making the memory reusable through the custom allocator, a deterministic memory footprint can be achieved.

这篇关于有可能使用shared_ptr的对象池模式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆