gpt4 book ai didi

c++ - 删除空指针是否安全?

转载 作者:太空宇宙 更新时间:2023-11-04 12:38:56 26 4
gpt4 key购买 nike

假设我有以下代码:

void* my_alloc (size_t size)
{
return new char [size];
}

void my_free (void* ptr)
{
delete [] ptr;
}

这样安全吗?或者必须在删除之前将 ptr 转换为 char*

最佳答案

C++ 标准未定义通过 void 指针删除 - 参见第 5.3.5/3 节:

In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.

及其脚注:

This implies that an object cannot be deleted using a pointer of type void* because there are no objects of type void

.

关于c++ - 删除空指针是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55177445/

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