带有编译时数组的自定义分配器

Custom allocator with compile time array

本文关键字:自定义 分配器 数组 编译      更新时间:2023-10-16

我想要有一个定义的分配限制(对于我的µC)来分配"动态"内存。

我的代码:

template<class T, size_t COUNT>
class SimpleAllocator
{
public:
  using value_type = T;
  template<class U>
  struct rebind
  {
    using other = SimpleAllocator<U, COUNT>;
  };
  SimpleAllocator() noexcept
  {
  }
  template<class U, size_t COUNT_U>
  SimpleAllocator(SimpleAllocator<U, COUNT_U> const &other) noexcept
  {
  }
  value_type* allocate(std::size_t p_Count)
  {
    return nullptr;
  }
  void deallocate(value_type* p_Chunk, std::size_t) noexcept
  {
  }
  T m_Chunks[COUNT];
};

如果我将这个分配器与智能指针函数一起使用:std::allocate_shared,我会得到一个编译器错误:

error: constructor for 'SimpleAllocator<std::_Sp_counted_ptr_inplace<int, 
  SimpleAllocator<int, 10>, __gnu_cxx::_Lock_policy::_S_atomic>, 10>' must
  explicitly initialize the member 'm_Chunks' which does not have a default
  constructor

我理解这个错误,但我无法解决它。我如何初始化这样的对象:

std::_Sp_counted_ptr_inplace<int, SimpleAllocator<int, 10>,
  __gnu_cxx::_Lock_policy::_S_atomic>

活生生的例子。

您不想初始化分配器中的任何对象,只需要分配内存。所以你必须更换这个

T m_Chunks[COUNT];

例如

alignas(T) char m_Chunks[COUNT * sizeof(T)];

并相应地更新所有的记账(您还没有显示)。

也就是说,在分配器内部有一个缓冲区本身不是一个好主意(除非你确切地知道自己在做什么)。分配器应该是一个轻量级对象,因为它按值存储在容器中,并在许多操作中被复制。