Re: when does exception destructor fire
andrew_nuss@yahoo.com ha scritto:
On May 13, 9:01 am, Alberto Ganesh Barbati <AlbertoBarb...@libero.it>
wrote:
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
I have to apologize. It seems that the standard is clearer than I
thought and that the strategy I exposed in the previous message is not
allowed. The key paragraph is 15.1/4:
"The memory for the temporary copy of the exception being thrown is
allocated in an unspecified way, except as noted in 3.7.3.1. The
temporary persists as long as there is a handler being executed for that
exception. [...] When the last handler being executed for the exception
exits by any means other than throw; the temporary object is destroyed
and the implementation may deallocate the memory for the temporary
object; any such deallocation is done in an unspecified way. [...]"
So it seems that if you catch the object by reference, no copy of the
thrown object will be made.
My Exception objects hold JNI jobject localrefs, and delete the
references in the destructor. Your strategy item #3 implies that I
must implement a copy constructor and an assignment operator doesn't
it. Why? Because otherwise the destructor fires twice in #4 and #6
against the same jni localref.
If your class holds references or pointers to anything, it is *always*
good programming practice to have proper copy-constructor and assignment
operator. Even you think you don't need them, do write them. Period.
Alternatively, mark the class as non-copyable by declaring private
copy-ctor and assignment, but never, never, NEVER write such a class
without them (and I mean *both* of them). The compiler can silently do
copies in so many places that you definitely want to have control over
it. Forgetting a "&" can happen, so don't rely on that!
HTH,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]