Search code examples
c++exceptionconstructornew-operatordelete-operator

Calling of delete after construction throwing an exception


I'm reading Effective C++ 3rd Edition, item52 "Write placement delete if you write placement new".

I want to how to make the operator delete automatically called after construction throwing an exception.

#include <iostream>
using namespace std;

class A {
    int i;
public:
    static void* operator new(std::size_t size) throw(std::bad_alloc) {
        return malloc(size);
    }
    static void operator delete(void* p) throw() {
        cout << "delete" << endl;
        free(p);
    }
    A() {
        throw exception();
    }
};

int main() {
    A* a = new A;
}

The above codes only output:

terminate called after throwing an instance of 'std::exception'
  what():  std::exception
[1]    28476 abort      ./test_clion

Solution

  • Reference: operator delete, operator delete[]

    I should write new in try {}. Know too little about exceptions for now.

    #include <iostream>
    using namespace std;
    
    class A {
        int i;
    public:
        static void* operator new(std::size_t size) throw(std::bad_alloc) {
            return malloc(size);
        }
        static void operator delete(void* p) throw() {
            cout << "delete" << endl;
            free(p);
        }
        A() {
            throw exception();
        }
    };
    
    int main() {
        try {
            A* a = new A;
        } catch (const exception&) {
    
        }
    }
    

    And the output:

    delete