下面的代码是否表明存在内存泄漏?
未调用 Test 类的析构函数(屏幕上没有出现输出),并且我假设分配给 Int 类数组的所有内存都没有返回给系统?我的假设正确吗?如果发生异常,我该如何收回构造函数中分配的资源?
#include <iostream>
using namespace std;
class Int{
public:
int v;
Int(){
cout<<"inside Int constructor ..."<<endl;
}
~Int(){
cout<<"inside Int destructor ..."<<endl;
}
};
class Test{
public:
Int* a;
Test(){
a=new Int[10];
cout<<"inside Test constructor ..."<<endl;
throw(0);
}
~Test(){
delete [] a;
cout<<"inside Test destructor ..."<<endl;
}
};
int main(){
try{
Test T;
}
catch (int e){
cout<<"Error!!!"<<endl;
}
return 0;
}
最佳答案
不会调用析构函数,因为该对象从未完全构造。在部分构造的对象上调用它可能会更危险,因为它会尝试撤消从未完成的事情。作为程序员,您有责任确保在发生异常时构造函数不会泄漏内存(或任何其他资源)。
但是,基类和成员变量的析构函数将会被调用!这就是为什么在大多数情况下最好依赖智能指针或容器,它们将为您处理资源管理。尝试像这样改变你的类(class):
#include <memory>
class Test{
public:
std::unique_ptr<Int[]> a;
Test(){
a=std::make_unique<Int[]>(10);
cout<<"inside Test constructor ..."<<endl;
throw(0);
}
~Test(){
//no need to delete[] a;
cout<<"inside Test destructor ..."<<endl;
}
};
这是一个双赢的局面。您将看到 Int
的析构函数将被调用,并且您无需手动处理内存。
关于c++ - 在 C++ 类的构造函数中引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39800189/