c++中new bad_alloc 异常处理
如果发生了内存分配错误,new会抛出bad_alloc异常,并且a_ptr is nullptr, 所以这个时候不需要delete。然而A的构造函数后面的异常抛出时,a对象已经构造,a_ptr is not nullptr,所以需要调用delete。
#include <bits/stdc++.h>
using namespace std;
class A {
public:
A() {
std::cout << "construct ... A" << "\n";
throw std::bad_alloc();
}
~A() {
std::cout << "deconstruct A ..." << "\n";
}
};
int main(void) {
A *a_p = nullptr;
try {
a_p = new A();
throw exception();
} catch (const bad_alloc &e) {
std::cout << "eb " << e.what() << std::endl;
} catch (const exception &e) {
std::cout << "e " << e.what() << std::endl;
delete a_p;
}
return 0;
}