gpt4 book ai didi

c++ - 为什么在调用allocator类的deallocate方法时不允许指针为null?

转载 作者:搜寻专家 更新时间:2023-10-31 01:02:05 25 4
gpt4 key购买 nike

我可以在阅读时跨过这个C++ Primer :

The pointer we pass to deallocate cannot be null; it must point to memory allocated by allocate.

我检查了 deallocate 的源代码,发现了这个:

// __p is not permitted to be a null pointer.
void
deallocate(pointer __p, size_type)
{ ::operator delete(__p); }

好的,所以我知道 delete 表达式和 operator delete() 之间存在区别。 delete 表达式可用于空指针。但是,此函数直接调用全局 operator delete() 函数。然而,我用谷歌搜索了这个问题并找到了一篇博文 here这也说明全局运算符 delete 方法也会检查空指针,如下所示:

void
operator delete (void* ptr) throw ()
{
if (ptr)
std::free (ptr);
}

此外,具有讽刺意味的是,我还发现了here在空指针上调用 std::free 也没有任何效果......所以我的问题是,为什么不允许 __p 成为空指针?

最佳答案

根据 documentation for std::allocator::deallocate :

Deallocates the storage referenced by the pointer p, which must be a pointer obtained by an earlier call to allocate(). The argument n must be equal to the first argument of the call to allocate() that originally produced p.

Calls ::operator delete(void*), but it is unspecified when and how it is called.

在我看来,此规范允许分配器假定指针不为空。您正在查看的分配器直接将指针传递给 ::operator delete(),但并非所有分配器都是这种情况。

关于c++ - 为什么在调用allocator类的deallocate方法时不允许指针为null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27829452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com