メモリ内で任意の型の配列が続くクラスを実装しようとしています。
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>));
}
しかし今、標準に準拠したallocator を使用してこれを実装するにはどうすればよいSomeAllocatorですか?
SomeAllocator::rebind<char>::other::allocateどのタイプのオブジェクトにも適切に整列されたメモリを返すことが保証されていますか? もしそうなら、char型のアロケータを使用するだけで安全ですか? そうでない場合、代替手段はありますか、それとも一般的にアロケーターではこのタスクは不可能ですか? (最悪の場合、ポインタをuintptr_t手動でキャストして整列させることができると思いますが、もっと良い方法があるかどうか疑問に思っています。)