C ++有状态分配器解除分配问题 [英] C++ stateful allocator de-allocate issues
问题描述
这个问题是我对标准如何使用自定义分配器的误解。我有一个有状态的分配器,它保持分配的块的向量。此向量在分配时被推入,并在解除分配期间进行搜索。
This issue is my misunderstanding of how the standard is using my custom allocator. I have a stateful allocator that keeps a vector of allocated blocks. This vector is pushed into when allocating and searched through during de-allocation.
从我的调试看来,对象的不同实例(这是不同的)在取消分配时被调用。一个示例可能是调用MyAllocator(this * = 1)分配20个字节,然后一段时间后调用MyAllocator(this * = 2)取消分配先前分配的20个字节。显然,MyAllocator(this * = 2)中的向量不包含其他分配器分配的20字节块,因此无法取消分配。我的理解是C ++ 11允许有状态分配器,这是怎么回事,以及如何解决此问题?
From my debugging it appears that different instances of my object (this*'s differ) are being called on de-allocation. An example may be that MyAllocator (this* = 1) is called to allocate 20 bytes, then some time later MyAllocator (this* = 2) is called to de-allocate the 20 bytes allocated earlier. Abviously the vector in MyAllocator (this* = 2) doesn't contain the 20 byte block allocated by the other allocator so it fails to de-allocate. My understanding was that C++11 allows stateful allocators, what's going on and how do i fix this?
我已经将运算符==设置为仅在以下情况下返回true这==& rhs
I already have my operator == set to only return true when this == &rhs
伪代码:
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;
}
我在gcc上将此分配器用于std :: vector。据我所知,没有发生任何奇怪的重新绑定的事情
Im using this allocator for an std::vector, on gcc. So as far as i know no weird rebind stuff is going on
推荐答案
正如@Igor所述,分配器必须是可复制的。重要的是,尽管它们必须在副本之间共享状态,即使它们是从副本中复制的也是如此。在这种情况下,修复很容易,我按照建议将块向量设为了shared_ptr,然后将所有对该向量的更新复制到同一向量上,因为它们都指向同一事物。
As @Igor mentioned, allocators must be copyable. Importantly though they must share their state between copies, even AFTER they have been copied from. In this case the fix was easy, i made the blocks vector a shared_ptr as suggested and then now on copy all the updates to that vector occur to the same vector, since they all point to the same thing.
这篇关于C ++有状态分配器解除分配问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!