假设我声明了一个 char 指针,并在没有调用 new 的情况下对其调用 delete。这会导致问题吗?
char* myptr;
if (condition)
//do something involving myptr = new char[SIZE];
else
//do something that doesnt involve myptr
//do more stuff
delete[] myptr;
我没有删除 if 下的 myptr,因为如果 condition
为真,则 //do more stuff
中的另一个指针可以指向它。显然,如果 condition
为真,这就可以正常工作,因为在 myptr
上调用了“new”。如果我进入 else 条件,其中 myptr
未被使用,删除 myptr
是否不好?
最佳答案
这是未定义的行为。指针必须来自new
或必须是空指针。
标准 (N3797) 5.3.5[expr.delete]
/2
If the operand has a class type, the operand is converted to a pointer type by calling the above-mentioned conversion function, and the converted operand is used in place of the original operand for the remainder of this section. In the first alternative (delete object), the value of the operand of delete may be a null pointer value, a pointer to a non-array object created by a previous new-expression, or a pointer to a subobject (1.8) representing a base class of such an object (Clause 10). If not, the behavior is undefined.
[...]
底部遗漏的部分与 delete []
相同。
删除只对
有效- 空指针
- 你从新得到的指点
- 或指向上述内容的基类指针。
空指针:
要跟进空指针,在空指针上调用 delete
是一个空操作,之后指针仍然是空指针(不需要重新分配 nullptr
给它).这至少对于标准的 delete
和释放函数是有保证的。如果您定义自定义的,您也应该妥善处理。
标准 5.3.5 [expr.delete]
/7
If the value of the operand of the delete-expression is not a null pointer value, then:
- [...]
Otherwise, it is unspecified whether the deallocation function will be called. [ Note: The deallocation function is called regardless of whether the destructor for the object or some element of the array throws an exception. — end note ]
所以 delete
可能什么都不做,或者可能用空指针调用释放函数。接下来让我们看一下该函数:
标准 3.7.4.2 [basic.stc.dynamic.deallocation]
/3
If a deallocation function terminates by throwing an exception, the behavior is undefined. The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect.
[...]
明确提到它没有效果。
注意:如果您定义自己的自定义释放函数,您应该确保以相同的方式处理它。不正确处理空指针将是邪恶的。
关于c++ - 当我在 C++ 中对未初始化的指针调用 "delete"时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27133056/