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

问题描述 投票:1回答:1

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

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));

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

c++ c++11 allocator pointer-arithmetic
1个回答
0
投票

引用YSCs评论以回答这个问题:

他们不鼓励“标准”操作的指针算术。处理未初始化的存储分配不是。 IMO,分配器的分配函数中的指针算法如果简单易读则完全没问题。

© www.soinside.com 2019 - 2024. All rights reserved.