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

后端 未结 3 1845
温柔的废话
温柔的废话 2021-01-12 02:39

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

When the exception is

3条回答
  •  无人共我
    2021-01-12 03:30

    The destructor is called before calling to the delete operator. See cppreference - delete expression

    If expression is not a null pointer, the delete expression invokes the destructor (if any) for the object that's being destroyed, or for every element of the array being destroyed (proceeding from the last element to the first element of the array). After that, unless the matching new-expression was combined with another new-expression (since C++14) the delete expression invokes the deallocation function, either operator delete (for the first version of the expression) or operator delete[] (for the second version of the expression).

    Due to this order of operations, the destructor is called and throws an exception before your overloaded version of the delete operator is called.

提交回复
热议问题