14.6 예외처리의 위험성과 단점
#include <iostream>
#include <memory>
using namespace std;
class A
{
public:
~A()
{
throw "error";
}
};
int main()
{
try
{
int *i = new int[1000000];
unique_ptr<int> up_i(i); // 이렇게 선언하면 delete가 필요 없다. 영역을 벗어나면 메모리 지워줌(throw로 error가 발생해도)
throw "error"; // 에러가 발생하면 delete하기 전에 catch로 가기때문에 메모리누수가 생김.
delete[] i;
}
catch(...)
{
cout << "Catch" << "\n";
}
return 0;
}
#include <iostream>
#include <memory>
using namespace std;
class A
{
public:
~A()
{
throw "error"; // 소멸자 안에서 throw하는 것은 금기시되는 것. 소멸자에서는 예외를 던질 수 없다.
}
};
int main()
{
try
{
A a;
}
catch(...)
{
cout << "Catch" << "\n";
}
return 0;
}