C++中因为抛出异常造成的内存泄漏
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
class Err{
string s;
public:
Err(string s="error"){
cout<<s<<endl;
}
};
class Giant{
public:
Giant(){
cout<<"Giant构造函数"<<endl;
}
~Giant(){
cout<<"Giant析构函数"<<endl;
}
};
class Big{
public:
Big()throw(Err){
cout<<"Big构造函数"<<endl;
throw Err();
}
~Big(){
cout<<"Big析构函数"<<endl;
}
};
class MyClass{
private:
Giant* giant;
Big* big;
public:
MyClass():giant(new Giant() ),big(new Big() ){
cout<<"MyClass构造函数"<<endl;
}
~MyClass(){
cout<<"MyClass析构函数"<<endl;
delete giant;
delete big;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
try{
MyClass myobject;
}catch(Err){
cout<<"捕获了异常"<<endl;
}
return 0;
}
#include <string>
#include <iostream>
using namespace std;
class Err{
string s;
public:
Err(string s="error"){
cout<<s<<endl;
}
};
class Giant{
public:
Giant(){
cout<<"Giant构造函数"<<endl;
}
~Giant(){
cout<<"Giant析构函数"<<endl;
}
};
class Big{
public:
Big()throw(Err){
cout<<"Big构造函数"<<endl;
throw Err();
}
~Big(){
cout<<"Big析构函数"<<endl;
}
};
class MyClass{
private:
Giant* giant;
Big* big;
public:
MyClass():giant(new Giant() ),big(new Big() ){
cout<<"MyClass构造函数"<<endl;
}
~MyClass(){
cout<<"MyClass析构函数"<<endl;
delete giant;
delete big;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
try{
MyClass myobject;
}catch(Err){
cout<<"捕获了异常"<<endl;
}
return 0;
}