交代背景
最近组里小伙伴通过组播技术实现发送同一报文到多个接收者,Receiver端会申请内存接收UDP数据包并存入指定Queue中,待用户从Queue中取出数据后会将这块内存回收。上述数据发送功能主要用于无人车仿真系统中,将NPC车位置数据、无人车采集到的Lidar数据和图像数据等发送到核心算法决策模块,由于数据发送的频率会影响算法最终的推理结果,因此内存的申请和释放会相当频繁(基本10ms会发送一次),小伙伴采用内存池来提升性能和避免内存碎片的问题。
小伙伴设计将内存申请结果会存放于std::vector中(关于这种设计是否合理暂且不表,只是为了引出本文的讨论问题),因此实现了自定义Allocator以使用内存池来管理内存。
Allocator是什么和如何自定义Allocator
下述是维基百科对Allocator的定义:
In C++ computer programming, allocators are a component of the C++ Standard Library. The standard library provides several data structures, such as list and set, commonly referred to as containers. A common trait among these containers is their ability to change size during the execution of the program. To achieve this, some form of dynamic memory allocation is usually required. Allocators handle all the requests for allocation and deallocation of memory for a given container. The C++ Standard Library provides general-purpose allocators that are used by default, however, custom allocators may also be supplied by the programmer.
简而言之,为了使STL容器具有动态增加和删除元素的能力,Allocator需要提供内存的申请和释放功能,C++标准库提供了默认的Allocator(正如下面代码是MSVC中std::vector的定义),所以容器的常规使用并不需要自定义Allocator。
// CLASS TEMPLATE vector
template <class _Ty, class _Alloc = allocator<_Ty>>
class vector { // varying size array of values
... ...
}
Allocator最核心的是实现allocate方法以分