避免動態分配內存後因異常而導致的內存泄露

 當在一個函數中動態創建一個對象時如果在delete之前發生異常就會導致內存泄露,原因很簡單,因爲程序沒有處理delete,如果是局部變量,則會保證局部變量的釋放.所以我們需要定義一個類來管理NEW來的內存通過在函數中定義局部對象,在異常發生的時候就會自動釋放.也就是說自動調用他的析構函數.我們可以在它的構造函數中去NEW一個我們要得對象,而類中保留一個數據成員存放NEW返回的指針,析構時DELETE指針就好了.

 

#include "iostream"
using std::endl;
using std::cout;
using std::cin;
using std::bad_alloc;
using std::ostream;

class fushu{
public:
    fushu(
int x,int y);
    friend ostream
& operator<<(ostream& out,const fushu& linshi);
    fushu 
operator+(fushu& anotherfu);    
    
~fushu()
    
{
        cout
<<"fushu destroy!"<<endl;
    }

    
int a;
    
int b;
}
;

fushu fushu::
operator+(fushu& anotherfu)
{
    fushu c(
0,0);
    
if (a==anotherfu.a && b==anotherfu.b) {
        
throw (anotherfu);
    }

    c.a
=a+anotherfu.a;
    c.b
=b+anotherfu.b;
    
return c;
}

fushu::fushu(
int x,int y): a(x),b(y)
    
{
        cout
<<"fushu constrct!"<<endl;
    }


ostream
& operator<<(ostream& out,const fushu& linshi)
{
    
out<<linshi.a<<" "<<linshi.b<<endl;
    
return out;
}


class auto_p{
public:
    auto_p(fushu
& m);
    auto_p(fushu
* mm);
    
~auto_p();

    fushu
* p;
}
;

auto_p::auto_p(fushu 
&m)
{
    p
=new fushu(m);
    cout
<<"auto_p construct!"<<endl;
}


auto_p::auto_p(fushu
* mm)

    p
=mm;
    cout
<<"auto_p construct with fushu *"<<endl;
}


auto_p::
~auto_p()
{
    delete p;
    cout
<<"auto_p destroy!"<<endl;
}


void fun()
{
    fushu fu(
10,20);
    auto_p mauto(fu);
    auto_p mautoptr(
new fushu(10,20));
    cout
<<(*mautoptr.p+*mauto.p)<<endl;
}


int main()
{
    
try{
        fun();
       }

    
catch (fushu & aaa) {
      cout
<<aaa.a<<"and"<<aaa.b<<"same to fushu with mauto point to!"<<endl;
    }

    
return 0;
}

 

這樣當異常發生時,會自動調用AUTO_P的析構函數,因爲對象是局部的,而析構函數又會DELETE FUSHU的對象,從而達到目的.

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章