【发布时间】:2018-01-28 16:08:39
【问题描述】:
我正在阅读 Effective C++ 第 3 版,第 52 项“如果您编写位置新,则写入位置删除”。
我想知道如何让操作符delete在构造抛出异常后自动调用。
#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
【问题讨论】:
-
如果分配内存失败,则无法释放它
-
Delete 在构造函数抛出时自动调用。顺便说一下,这个例子实际上并不是placement new,也不能直接调用placement delete。但是如果它是placement new,并且构造函数抛出了一个异常,编译器会调用它的placement delete,因此是你书中的建议。
标签: c++ exception constructor new-operator delete-operator