怎么能够在异常出现的情况下也能够释放堆内存资源?--------------智能指针 try-finally
对于出现异常时,不能释放堆内存的问题:
例如:
#include <iostream> |
02 |
using namespace std; |
03 |
class normal_pointer_example |
04 |
{ |
05 |
public : |
06 |
normal_pointer_example(){cout<< "构造函数执行!\n" ;} |
07 |
~normal_pointer_example(){cout<< "析构函数执行!\n" ;} |
08 |
}; |
09 |
class normal_pointer_wrong{}; //normal_pointer_wrong异常 |
10 |
bool quit; |
11 |
void quit_func() |
12 |
{ |
13 |
if (quit== true ) |
14 |
cout<< "调用quit_func函数!\n" ; |
15 |
throw normal_pointer_wrong(); |
16 |
} |
17 |
int main() |
18 |
{ |
19 |
try |
20 |
{ |
21 |
normal_pointer_example *Npointer= new normal_pointer_example; |
22 |
quit= true ; |
23 |
quit_func(); |
24 |
delete Npointer; |
25 |
} |
26 |
catch (normal_pointer_wrong) |
27 |
{ |
28 |
cout<< "输出normal_pointer_wrong异常!!\n" ; |
29 |
} |
30 |
return 0; |
31 |
} |
该程序的输出结果为:
我们可以用try-finally 因为finally中的是一定执行的(前提是,你写的try-finally的位置要对)
比如:
#include <iostream>
using namespace std;
class normal_pointer_example
{
public:
normal_pointer_example(){cout<<"构造函数执行!\n";}
~normal_pointer_example(){cout<<"析构函数执行!\n";}
};
class normal_pointer_wrong{};//normal_pointer_wrong异常
bool quit;
void quit_func()
{
if(quit==true)
cout<<"调用quit_func函数!\n";
throw normal_pointer_wrong();
}
normal_pointer_example *Npointer=new normal_pointer_example;
void f()
{
__try
{
}
__finally
{
delete Npointer;
}
}
int main()
{
try
{
quit=true;
quit_func();
delete Npointer; //有异常出现时,这句话不在执行
}
catch (normal_pointer_wrong)
{
bool exceFlag=true;
cout<<"输出normal_pointer_wrong异常!!\n";
if(exceFlag)
f();
}
return 0;
}
这样就能释放堆内存上的资源了;
另外 如果对智能指针熟悉的话,我们还可以运用智能指针,这样能使程序更加简单:
#include <iostream>
#include <memory>
using namespace std;
class normal_pointer_example
{
public:
normal_pointer_example(){cout<<"构造函数执行!\n";}
~normal_pointer_example(){cout<<"析构函数执行!\n";}
};
class normal_pointer_wrong{};//normal_pointer_wrong异常
bool quit;
void quit_func()
{
if(quit==true)
cout<<"调用quit_func函数!\n";
throw normal_pointer_wrong();
}
int main()
{
try
{
auto_ptr<normal_pointer_example> Apointer (new normal_pointer_example); //智能指针的使用,注意其使用的特别性!
quit=true;
quit_func();
//delete Npointer;
}
catch (normal_pointer_wrong)
{
cout<<"输出normal_pointer_wrong异常!!\n";
}
return 0;
}
运行智能指针,可以不必考虑那么多了,这就是智能指针的好处!