为什么在调用allocator类的deallocate方法时不允许指针为null?
Why is a pointer not permitted to be null when calling the deallocate method of the allocator class?
我可以边看边看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()
函数。然而,我用谷歌搜索了这个问题,发现了一个博客 post 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++ 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()
函数。然而,我用谷歌搜索了这个问题,发现了一个博客 post 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 toallocate()
that originally produced p.Calls
::operator delete(void*)
, but it is unspecified when and how it is called.
在我看来,此规范允许分配器假定指针不为空。您正在查看的分配器直接将指针传递给 ::operator delete()
,但并非所有分配器都是如此。