2016-09-30 68 views
1

下面的代码是否表示内存泄漏?在C++类的构造函数中抛出异常

不调用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; 
}  

回答

1

析构函数未被调用,因为该对象从未完全构造。在部分构造的对象上调用它可能会更危险,因为它会试图消除从未完成的事情。作为一名程序员,确保没有内存(或任何其他资源)在构造函数中发生异常时会泄漏。

但是,将会调用基类和成员变量的析构函数!这就是为什么在大多数情况下最好依靠智能指针或容器来处理资源管理。尝试改变你这样的课程:

#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的析构函数将被调用,并且您不需要手动处理内存。

0

我想出了一个解决方案,但不知道这是一个好的设计或正确的方法来做到这一点。你能评论吗?

#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(){ 
     try{ 
      a=new Int[10]; 
      cout<<"inside Test constructor ..."<<endl; 
      throw(0); // exception is thrown 
      } 

     catch (int e){ 
       delete [] a; 
       cout<<"Error!!!"<<endl; 
      } 
     } 

    ~Test(){ 
     delete [] a; 
     cout<<"inside Test destructor ..."<<endl; 
    } 
}; 

int main(){ 

     Test T; 


     return 0; 
}  
相关问题