问题
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 ????????????
}
回答1:
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.
回答2:
Operator delete
is noexcept
since C++11, so it doesn't throw, see http://en.cppreference.com/w/cpp/memory/new/operator_delete
If operator delete
throws, then you can end up throwing in destructor, and all bets are off.
来源:https://stackoverflow.com/questions/29475395/c-can-operator-delete-fails-and-if-not-why