【发布时间】:2021-04-04 22:19:15
【问题描述】:
在reading many questions about 指针比较之后,我开始意识到我的许多自定义分配器都会进行未指定行为的比较。一个例子可能是这样的:
template <int N, int CAPACITY>
class BucketList
{
struct Bucket
{
Bucket* next { nullptr }; // The next bucket, to create a linked list.
size_t size { 0 }; // Size allocated by the bucket.
uint8_t data[CAPACITY] { 0 };
};
Bucket* free; // The first bucket that has free space.
Bucket* next; // The next bucket, to create a linked list.
public:
BucketList()
{
this->next = new Bucket;
this->free = this->next;
}
uint8_t* allocate()
{
auto* bucket = this->free;
if (bucket->used + N >= CAPACITY)
{
bucket->next = new Bucket;
this->free = bucket->next;
bucket = bucket->next;
}
uint8_t* base = bucket->data + bucket->used;
bucket->used_size += N;
return base;
}
uint8_t* deallocate(uint8_t* ptr)
{
auto* bucket = this->next;
while (bucket && !(bucket->data <= ptr && ptr < bucket->data + CAPACITY))
bucket = bucket->next;
if (bucket)
// Bucket found! Continue freeing the object and reorder elements.
else
// Not allocated from here. Panic!
}
// And other methods like destructor, copy/move assignment, and more...
};
allocate 函数从分配的数组中返回一小块数据。为了解除分配,它通过检查指针的地址是否在桶的地址范围内(即(bucket->data <= ptr && ptr < bucket->data + CAPACITY))来检查指针是否来自桶。但是,所有存储桶都来自不同的分配,因此未指定此比较。
如果可能的话,我不想更改界面。我 also read 可以使用 std::less 来获得指针类型的严格总顺序,但我无法理解这是否会解决我的问题或只是进行指定的比较。
是否有正确的方法来检查指针是否属于已分配的块(以及指针是否不属于块)?
【问题讨论】:
-
stackoverflow.com/questions/64042325/… 的副本。 是否有正确的方法来检查指针是否属于已分配的块内没有。
标签: c++ pointers memory-management language-lawyer