Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ can operator delete fails and if not why?

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?

Also what did ISO standard says about this?

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 ????????????
}
like image 246
AnArrayOfFunctions Avatar asked Nov 29 '25 01:11

AnArrayOfFunctions


1 Answers

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

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

emphasis mine

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

like image 139
NathanOliver Avatar answered Nov 30 '25 13:11

NathanOliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!