Re: when does exception destructor fire
andrew_nuss@yahoo.com ha scritto:
class MyException {
std::string msg;
public:
MyException (char const* str) : msg(str) {}
std::string GetMsg () const { return msg; }
};
When we have code that does:
....
char temp[256];
... // fill temp with sprintf()
throw MyException(temp);
Where on the stack does thrown MyException live? When does it go out
of scope? When does the destructor for MyException "fire", causing
its std::string data member to be destroyed? I mean, where does the
compiler put the exception object.
Question is: why do you ask? You shouldn't bother. If you don't do
anything fancy, the compiler will just do the right thing for you.
Anyway, as you are curious, let me say that the Standard is deliberately
vague in order to allow different implementation strategies. For
example, one possible strategy might be this:
1) the exception object is constructed in the stack of the throwing function
2) the catch handler that will catch the exception is determined
3) the exception object is copied in the stack in the catch handler
4) control flows is transferred to the catch handler. In this phase
stack unrolling happens, in particular every local object in the
throwing function *including* the original exception object are destroyed
5) the catch handler is executed
6) once the control flow leaves the catch handler (for whatever reason)
the copy of the exception object is destroyed
compiler put the exception object. By the way, is there any harm in
GetMsg() above returning a const reference?
In this respect, an exception object is not different from any other
object. The usual precautions for returning a reference to a data member
apply: it's safe to access the returned reference as long as the object
is in scope.
HTH,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]