C++因为发生异常很可能造成内存泄漏

#include <boost/date_time.hpp>
using namespace boost::posix_time;
using namespace boost;


class ReleaseResource
{
public:
ReleaseResource();
~ReleaseResource();

void DisplayMsg();

private:
char *m_szpString;

};

ReleaseResource::ReleaseResource()
{
m_szpString = new char[40];
}

ReleaseResource::~ReleaseResource()
{
if (m_szpString)
{
delete m_szpString;
}
}

void ReleaseResource::DisplayMsg()
{
cout << "Display message" << endl;
string str = "null exception" ;

throw str;
}

int _tmain(int argc, _TCHAR* argv[])
{
try
{
{
ReleaseResource *myResource = new ReleaseResource(); //将对象分配在堆上的时候,当发生异常的时候,由于对象的析构函数没有调用delete,很可能造成内存泄漏的问题
myResource->DisplayMsg();
}
}
catch (string ex)
{
cout << ex << endl;
}

int wait;
cin >> wait;

return 0;
}

posted @ 2013-07-01 21:05  Predator  阅读(436)  评论(0编辑  收藏  举报