gpt4 book ai didi

C++ 可以删除运算符失败,如果不能,为什么?

转载 作者:行者123 更新时间:2023-11-30 01:49:10 24 4
gpt4 key购买 nike

operator delete 是否可以在内存释放期间以其他方式抛出异常或信号?

operator delete 是否有可能以其他方式失败,在这种情况下它的默认行为是什么?

ISO 标准对此有何规定?

例如在 Windows 操作系统中 - C++ operator newoperator delete 通常通过函数 HeapAllocHeapFree 实现.后面的函数返回一个 bool 值,清楚地表明可能会失败。想象一下 C++ operator delete 会怎么写在上面:

void operator delete(void *pMem)
{
extern HANDLE hHeap;
extern DWORD dwFlags;

BOOL bSuccee = HeapFree(hHeap, dwFlags, pMem);

//return bSuccee ????????????
}

最佳答案

在 C++11 18.6 中,delete 被定义为 noexcept 函数。从5.3.5节删除

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. In the second alternative (delete array), the value of the operand of delete may be a null pointer value or a pointer value that resulted from a previous array new-expression.82 If not, the behavior is undefined. [ Note: this means that the syntax of the delete-expression must match the type of the object allocated by new, not the syntax of the new-expression. —end note

强调我的

从这里我们可以看出以不打算使用的方式使用 delete 是 UB。

关于C++ 可以删除运算符失败,如果不能,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29475395/

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