简体   繁体   English

C++分配器存储不同类型的对象

[英]C++ allocator to store objects of different types

I have a bunch of objects wrapped by unique_ptrs.我有一堆由 unique_ptrs 包裹的对象。
Each object is of its own type.每个 object 都有自己的类型。
I would like to create a kind of memory pool to store all those objects to avoid heap allocations for every last object.我想创建一种 memory 池来存储所有这些对象,以避免每个最后一个 object 的堆分配。 Like this:像这样:

Allocator allocator(1024);分配器分配器(1024); // should be extendable // 应该是可扩展的
unique_ptr< A > a = allocator.allocateAndWrapToUPtr< A >(); unique_ptr< A > a = allocator.allocateAndWrapToUPtr< A >();
unique_ptr< B > b = allocator.allocateAndWrapToUPtr< B >(); unique_ptr< B > b = allocator.allocateAndWrapToUPtr< B >();
C* c = allocator.allocate< C >(); C* c = allocator.allocate< C >();

As far as I can see allocators are specified as据我所见,分配器被指定为
template模板
class MyAllocator; class MyAllocator;
Hence they can store only objects of only one type.因此它们只能存储一种类型的对象。

Is it possible to implement "multitype" allocator?是否可以实现“多类型”分配器?

It is not possible to use one allocator everywhere around the project.不可能在项目周围的任何地方都使用一个分配器。 Dynamic allocator example can be found at dmitrysoshnikov.com/compilers/writing-a-pool-allocator, it allows to solve the initial problem with unique_ptrs.动态分配器示例可以在 dmitrysoshnikov.com/compilers/writing-a-pool-allocator 找到,它允许使用 unique_ptrs 解决初始问题。
But it is not stl compliant so can not be used for collections for example.但它不符合 stl 标准,因此例如不能用于 collections。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM