如何使用符合STL的分配器进行异构内存分配

Meh*_*dad 11 c++ memory-management allocator heterogeneous

我正在尝试通过一些任意类型的数组实现一个在内存中遵循的类:

template<class T>
class Buf
{
    size_t n;
    int refs;
    explicit Buf(size_t n) : n(n) { }
    // other declarations are here as appropriate

    // Followed in memory by:
    // T items[n];
};
Run Code Online (Sandbox Code Playgroud)

这很简单operator new:

template<class T>
Buf<T> *make_buf(size_t n)
{
    // Assume the caller will take care of constructing the array elements
    return new(operator new(sizeof(Buf<T>) + sizeof(T) * n)) Buf<T>(n);
}

template<class T>
void free_buf(Buf<T> *p)
{
    // Assume the caller has taken care of destroying the array elements
    p->~Buf<T>();
    return operator delete(p);
}

template<class T>
T *get_buf_array(Buf<T> *p)
{
    return reinterpret_cast<T *>(reinterpret_cast<char *>(p) + sizeof(Buf<T>));
}
Run Code Online (Sandbox Code Playgroud)

但是现在,我如何使用一些符合标准的分配器 来实现它SomeAllocator

是否保证SomeAllocator::rebind<char>::other::allocate会为任何类型的对象返回适当对齐的内存?如果是这样,我是否可以安全地使用某种char类型的分配器?如果没有,我有任何替代方案,或者一般情况下分配器是否无法执行此任务?(在最坏的情况下,我想我可以将指针转换为uintptr_t手动对齐它们,但我想知道是否有更好的方法.)

dav*_*pfx 0

恐怕您对 C++ 标准的要求做出了毫无根据的假设。您尝试做的事情可能一般来说是不可能的。

需要默认分配器(new 或 malloc)来返回指向适当对齐的内存块的指针any complete object type with a fundamental alignment requirement。尺寸必须是at least as large as the requested size. 自定义分配器有不同的要求,具体取决于它们分配的内容。不保证一种类型的分配器返回与另一种类型适当对齐的存储。当然,如果您是实现自定义分配器的人,则可以确保它返回您需要的内容。

编译器需要满足一些有关内存布局的约束,但它不能保证某些内容紧接着其他内容放入内存中。可以插入填充字节以满足对齐要求。

最近的 C++ 标准为处理对齐提供了相当多的支持。那里可能有一个答案给你。我怀疑这背后有一些您没有告诉我们的要求。也许还有另一种方法可以解决这个问题。