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

标签 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];
};

使用 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/

相关文章:

c++ - GCC:如何找到不丢弃目标文件的原因

C++ 结构声明和用法来保存 IP + 连接

c++ - 静态分配的内存在其范围结束后会发生什么?

c++ - 如何实现仅在堆栈上分配的字符串

c++ - std::vector 的第二个参数

c++ - 很难理解封装

c++ - 温索克 RIO : RIOReceive returns immediately with no bytesTransferred

memory-management - SSAS 和 Power BI 在内存使用方面的差异

c++ - 删除运算符如何在我的代码中工作?

c++ - 你如何声明一个分配器?