|
현재 영어 원서를 가지고 공부를 하고 있는데. 이 책이 해답지가 없어서 여기에 질문을 하고자 합니다.
오늘 첫 가입해서 아직 익숙하지 않습니다. 혹 제가 잘못된 게시판에서 글을 쓰고 있다면 말씀해주세요. 다음번에는 올바른 게시판에서 쓰겠습니다.
문제는 다음과 같네요.
Write a program illustrating that all destructors for objects constructed in a block are called before an exception is thrown from that block.
제 방식대로 번역을 해보자면...
모든 소멸자(destructors)가 block 내부에서 생성된 객체를, 해당 block에서 exception이 throw 되기 "전(before)"에 호출하십시오.
저 같은 경우 일단 stack unwinding을 써서 시도를 해봤는데, 소멸자가 exception이 throw 된 후에 호출이 되더군요. 혹시 다른 방법이 있을까요? 아니면 제 코드를 수정하면 될까요. 제 코드는 다음과 같습니다.
#include <iostream>
#include <stdexcept>
using namespace std;
class A
{
public:
A()
{
cout << "Ctor is created!" << endl;
}
~A()
{
cout << "Dtor is destroying!" << endl;
}
};
void function1() throw( runtime_error )
{
cout << "In our function1 throw exception!" << endl;
throw runtime_error("runtime_error in function");
}
void function2() throw( runtime_error )
{
A a;
cout << "In our function2" << endl;
function1();
}
int main()
{
try
{
cout << "function2 is called inside main" << endl;
function2();
}
catch( runtime_error &error)
{
cout << "Exception occurred!! " << error.what() << endl;
cout << "Exception is handled in main()" << endl;
}
return 0;
}
현재 결과값은 다음처럼 나오네요.
function2 is called inside main
Ctor is created!
In our function2
In our function1 throw exception!
Dtor is destroying! //소멸자가 exception이 throw된 후에 호출...
Exception occurred!! runtime_error in function
Exception is handled in main()
Press any key to continue . . .
|