// C++
#include <iostream>
using namespace std;
class Test
{
public:
~Test()
{
cout << "~Test" << endl;
}
};
void func()
{
throw "exception";
}
int main()
{
int* i = nullptr;
try
{
i = new int;
func();
delete i;
}
catch (const char* e)
{
delete i;
cout << e << endl;
}
}
// C++
#include <iostream>
using namespace std;
class RAII
{
public:
int* i;
RAII()
{
i = new int;
cout << "RAII 생성자" << endl;
}
~RAII()
{
delete i;
cout << "~RAII 소멸자" << endl;
}
};
void func()
{
throw "exception";
}
int main()
{
int* i = nullptr;
try
{
RAII raii;
func();
}
catch (const char* e)
{
cout << e << endl;
}
}
Output:
RAII 생성자
~RAII 소멸자
exception
// C++
#include <iostream>
using namespace std;
class Test
{
public:
~Test()
{
cout << "~Test" << endl;
}
};
void func()
{
throw "exception";
}
int main()
{
int* i = nullptr;
try
{
unique_ptr<Test> test(new Test()); // std
func();
}
catch (const char* e)
{
cout << e << endl;
}
}