自定义分配器没有指针算术

时间:2018-05-04 13:13:25

标签: c++ c++11 allocator pointer-arithmetic

我有一个自定义分配器类,看起来像这样:

class allocator {
private:
  char* memory;
  std::ptrdiff_t offset;
  std::size_t total_size;

public:
  allocator(std::size_t size) : total_size(size), offset(0) {
    memory = new char[size];
  }
  void* allocate(std::size_t size, std::size_t alignment) {
    // unimportant stuff

    void* current_address = &start_ptr[offset]; // --> OUCH, pointer arithmethic

    offset += size;
    // unimportant stuff
    return current_address;
  }

}

如上所示,我使用指针算法计算新分配的内存块的当前地址。 CppCoreGuidelines和许多其他指南不鼓励使用指针算术。那么还有另一种管理内存池的方法吗?

我在考虑使用std::vector<char>,因为它包含一个连续的内存块,并做这样的事情:

std::vector<char> memory;

void* current_address = &(memory.at(offset));

但这对我来说似乎没什么好看的。您对如何以安全的方式干净地管理内存池有任何想法吗?

1 个答案:

答案 0 :(得分:0)

引用Dim term As String Sheets("Sheet1").Select term = Range("A1").Value If InStr(.Value, "term") = 0 Then .EntireRow.Delete 的评论以回答此问题:

  

它们不鼓励使用“标准”操作的指针算法。交易   与未初始化的存储分配不是。 IMO,指针算法   在分配器的分配函数中,如果简单   阅读。