我正在尝试实现一个类,该类在内存中后跟某个任意类型的数组:
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
并手动对齐它们,但我想知道是否有更好的方法。)
最佳答案
我认为解决方案可能是创建一个概念性的早期阵列。
+-----------+
|Buf<T> |
+-------+---+---+-------+-------+
|T[0] | T[1] |T[2] | T[3]...
+-------+-------+-------+-------+
With the non-overlapping T[2], T[3], ... being the required array of T.
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];
};
损坏元素的数量为:-
const size_t lead = ( sizeof(Buf<T>) + sizeof(T) - 1) / sizeof(T);
终于可以访问i的原始内存了
(reinterpret_cast<T*>( this ) )[ i + lead ];
关于c++ - 如何使用符合 STL 的分配器进行异构内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25110398/