Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an overloaded delete not called when an exception is thrown in a destructor?

I've written the below code which overloads the new and delete operators and throws an exception in the destructor.

When the exception is thrown, why is the code in the delete operator not executed (and "bye" printed)?

If it shouldn't be executed, (how) is the memory freed? Is one of the other delete operators called? Would overloading one of them instead result in the corresponding code being executed? Or is the memory simply not freed because a failed destruction implies that maybe it shouldn't be?

#include <iostream>
using namespace std;
class A
{
public:
    A() { }
    ~A() noexcept(false) { throw exception(); }
    void* operator new (std::size_t count)
    {
        cout << "hi" << endl;
        return ::operator new(count);
    }
    void operator delete (void* ptr)
    {
        cout << "bye" << endl;
        return ::operator delete(ptr);
    }
    // using these (with corresponding new's) don't seem to work either
    // void operator delete (void* ptr, const std::nothrow_t& tag);
    // void operator delete (void* ptr, void* place);
};

int main()
{
    A* a = new A();
    try
    {
        delete a;
    }
    catch(...)
    {
        cout << "eek" << endl;
    }
    return 0;
}

Output:

hi
eek

Live demo.

I looked at:

  • throwing exceptions out of a destructor
  • How does C++ free the memory when a constructor throws an exception and a custom new is used
  • And others

But I couldn't find an answer to what exactly happens (1) for an exception in the destructor (as opposed to the constructor) and (2) with an overloaded delete.

I don't need a lecture on throwing an exception in a destructor being bad practice - I just ran into similar code and I'm curious about the behaviour.


I would prefer an answer supported by the standard or similar references, if such references exist.

like image 889
Bernhard Barker Avatar asked Aug 12 '17 20:08

Bernhard Barker


People also ask

Is the destructor called when delete is called?

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.

Can delete operator be overloaded?

New and Delete operators can be overloaded globally or they can be overloaded for specific classes. If these operators are overloaded using member function for a class, it means that these operators are overloaded only for that specific class.

What is difference between destructor and delete operator in C++?

So delete is for managing the dynamic memory, but the destructor is a method of the class itself, which is always called when the object is getting freed from the memory (stack or heap).

Can delete throw an exception C++?

A delete expression can throw, if the destructor itself throws, or a destructor of a sub object. But you should avoid throwing in a destructor. A delete expression might also have undefined behaviour if you try to delete a pointer that does not point to a valid object. An exception is nullptr , which is safe to delete.


2 Answers

The standard Draft N4296 5.3.5, pag 121 says:

[expr.delete] [ 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 ]

So the operator delete has to be called regardeless the destructor throws.

However, as has emerged from the comments, some compilers does not properly call the operator delete. This can be resolved as bug compiler.

Bug tested for:

  • GCC 4.8
  • Visual Studio 2015
like image 122
BiagioF Avatar answered Sep 20 '22 05:09

BiagioF


In the 1998 C++ standard (ISO/IEC 14882 First edition, 1998-09-01) the workings of a delete expression are stated quite simply in "Section 5.3.5 Delete [expr.delete]" in paras 6 and 7.

6 The delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted. In the case of an array, the elements will be destroyed in order of decreasing address (that is, in reverse order of the completion of their constructor; see 12.6.2).

7 The delete-expression will call a deallocation function (3.7.3.2).

In combination, these clauses require that destructor will be invoked (or destructors for an array) and that the deallocation function will be called unconditionally. There is no provision here for not calling the deallocation function if an exception is thrown.

In the 1998 standard, language lawyers and compiler developers will probably take delight in the sophistry of arguing a different interpretation than I've stated above. Fortunately, things are more explicit in later standards...

In Draft N4296 available from open-std.org the same clauses are expanded as follows: (from memory the wording in the official standard is the same, but I don't have a copy on my current machine)
(emphasis mine)

6 If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted. In the case of an array, the elements will be destroyed in order of decreasing address (that is, in reverse order of the completion of their constructor; see 12.6.2).

7 If the value of the operand of the delete-expression is not a null pointer value, then:

(7.1) - If the allocation call for the new-expression for the object to be deleted was not omitted and the allocation was not extended (5.3.4), the delete-expression shall call a deallocation function (3.7.4.2). The value returned from the allocation call of the new-expression shall be passed as the first argument to the deallocation function.

(7.2) - Otherwise, if the allocation was extended or was provided by extending the allocation of another new-expression, and the delete-expression for every other pointer value produced by a new-expression that had storage provided by the extended new-expression has been evaluated, the delete-expression shall call a deallocation function. The value returned from the allocation call of the extended new-expression shall be passed as the first argument to the deallocation function.

(7.3) - Otherwise, the delete-expression will not call a deallocation function (3.7.4.2).

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]

The note at the end spells out that the deallocation function must be called even if the destructor throws an exception.

I'm unsure offhand which evolution of the standard first spelled things out, but based on the above, the clauses will probably remain in Section 5.3.5 (tag [expr.delete]).

like image 26
Peter Avatar answered Sep 22 '22 05:09

Peter