C 状态分配器将问题分配问题



这个问题是我对标准如何使用自定义分配器的误解。我有一个状态分配器,可以保留分配的块的向量。在脱位分配期间分配和搜索时,将将该矢量推入。

从我的调试中,我的对象的不同实例(此*的不同(被称为脱位分配。一个例子是,Myallocator(This* = 1(被调用以分配20个字节,然后稍后的Myallocator(this* = 2(被调用以将其分配给前面分配的20个字节。Myallocator中的向量(* = 2(中的矢量不包含另一个分配器分配的20个字节块,因此无法分配分配。我的理解是C 11允许陈述的分配,这是怎么回事,我该如何解决?

我已经有操作员==仅在此==& rhs

时返回true

伪代码:

template<typename T>
class MyAllocator
{
    ptr allocate(int n)
    {
       ...make a block of size sizeof(T) * n
       blocks.push_back(block);
       return (ptr)block.start;
    }
    deallocate(ptr start, int n)
    {
        /*This fails because the the block array is not the
        same and so doesn't find the block it wants*/ 
        std::erase(std::remove_if(blocks.begin,blocks.end, []()
        {
            return block.start >= (uint64_t)ptr && block.end <= ((uint64_t)ptr + sizeof(T)*n);
        }), blocks.end);
    }
    bool operator==(const MyAllocator& rhs)
    {
        //my attempt to make sure internal states are same
        return this == &rhs;
    }
private:
  std::vector<MemoryBlocks> blocks;
}

IM在GCC上使用此分配器进行std :: vector。因此,据我所知,没有奇怪的重建

如@igor所述,分配器必须可复制。重要的是,尽管他们必须在副本之间共享自己的状态,即使他们被复制了。在这种情况下,修复程序很容易,我将blocks向量作为建议的共享_ptr,然后在复制该向量的所有更新中都发生在同一向量上,因为它们都指向同一内容。

最新更新