我正在尝试实现一个类,该类在内存中跟随一个任意类型的数组:
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];
};
这很容易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>));
}
但是现在,我如何使用一些符合标准的分配器 SomeAllocator
来实现这一点?
是否保证SomeAllocator::rebind<char>::other::allocate
将返回适合任何类型对象对齐的内存?如果是这样,我是否可以安全地使用某种 char 类型的分配器?如果没有,我是否有其他选择,或者一般分配器不可能完成这项任务?(在最坏的情况下,我想我可以将指针投射到uintptr_t
并手动对齐它们,但我想知道是否有更好的方法。)