在构造抛出异常后调用delete

时间:2017-08-20 13:21:59

标签: c++ exception constructor new-operator delete-operator

我正在阅读Effective C ++ 3rd Edition,item52"如果您编写新的",请写下展示位置删除。

我想如何在构造抛出异常后自动调用操作符删除。

#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;
}

以上代码仅输出:

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

1 个答案:

答案 0 :(得分:1)

参考:operator delete, operator delete[]

我应该在new中写try {}。暂时对例外情况知之甚少。

#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&) {

    }
}

输出:

delete