gpt4 book ai didi

c++ - 构造后调用 delete 抛出异常

转载 作者:行者123 更新时间:2023-11-28 05:01:35 26 4
gpt4 key购买 nike

我正在阅读 Effective C++ 第 3 版,第 52 条“Write placement delete if you write placement new”。

我想知道如何让operator 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

最佳答案

引用:operator delete, operator delete[]

我应该在 try {} 中编写 new。目前对异常知之甚少。

#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

关于c++ - 构造后调用 delete 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45782610/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com