C ++操作员可以删除失败,如果不是,为什么? [英] C++ can operator delete fails and if not why?

查看:91
本文介绍了C ++操作员可以删除失败,如果不是,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

操作员可以在内存取消分配期间删除引发异常或以其他错误方式发出信号吗?

Can operator delete throw an exception or signal in some other way of error during memory de-allocation?

以其他方式可能对操作员删除失败,在这种情况下,它是默认行为是什么?

In other way is it possible for operator delete to fail and what is it's default behavior in this case?

ISO标准对此有何看法?

Also what did ISO standard says about this?

例如在Windows操作系统中-C ++ operator new operator delete 是通常通过功能 HeapAlloc HeapFree 。后面的函数返回一个布尔值,该值清楚地表明可能发生故障。想象一下如何在其上编写C ++ operator delete

For example in Windows OS - C++ operator new and operator delete are normally implemented via functions HeapAlloc and HeapFree. The later function returns a boolean value which clearly indicates a fail is possible. Imagine how C++ operator delete will be written on it:

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节删除

In C++11 18.6 delete is defined as a noexcept function. From section 5.3.5 Delete


如果操作数具有类类型,则通过调用上述操作数将其转换为指针类型转换函数,在本节的其余部分中,将使用转换后的操作数代替原始操作数。在第一个替代方案(删除对象)中,删除操作数的值可以为空指针值,指向由先前的new表达式创建的非数组对象的指针或指向表示对象的子对象(1.8)的指针。此类对象的基类(第10条)。 如果不是,则行为是不确定的。在第二个替代方案(删除数组)中,删除操作数的值可以是空指针值,也可以是前一个数组new-expression产生的指针值。82如果不是,则行为未定义。 [注意:这意味着delete-expression的语法必须与new分配的对象的类型匹配,而不与new-expression的语法匹配。 —尾注

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

强调我的

从中我们可以看到使用UB并不打算使用delete的方式。

From this we can see using delete in a manner it isn't intended to be used is UB.

这篇关于C ++操作员可以删除失败,如果不是,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆