我有一个自定义的分配器类,它看起来如下所示:
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));但对我来说这一点也不太好。对于如何安全地管理内存池,你有什么想法吗?
发布于 2019-03-19 08:48:19
引用YSC的评论来回答这个问题:
它们不鼓励用于“标准”操作的指针算法。处理未初始化的存储分配不是。在分配器的分配函数中,指针算法如果读起来很简单的话,是非常好的。
https://stackoverflow.com/questions/50175854
复制相似问题