Possible Duplicate:
Will usinggoto
leak variables?
In the following example, when goto
is called to go "backwards", the destructor of A
is called. Why is it like that? Object a
is not leaving its scope, is it? Does the standard say anything about this behavior regarding goto
?
void f() { start: A a; goto start; }
While returning from a function, destructor is the last method to be executed. The destructor for the object “ob” is called after the value of i is copied to the return value of the function. So, before destructor could change the value of i to 10, the current value of i gets copied & hence the output is i = 3.
A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete .
yes, when you delete something, the destructor is called.
The object would be destroyed automatically and the destructor would be called as the object went out of scope when foo returns.
Paragraph 2:
On exit from a scope (however accomplished), objects with automatic storage duration (3.7.3) that have been constructed in that scope are destroyed in the reverse order of their construction. [ Note: For temporaries, see 12.2. —end note] Transfer out of a loop, out of a block, or back past an initialized variable with automatic storage duration involves the destruction of objects with automatic storage duration that are in scope at the point transferred from but not at the point transferred to. (See 6.7 for transfers into blocks). [Note: However, the program can be terminated (by calling std::exit() or std::abort() (18.5), for example) without destroying class objects with automatic storage duration. — end note ]
I think the important part is:
or back past an initialized variable with automatic storage duration involves the destruction
The lifetime of object a
starts from its declaration, and extends to the end of the block containing it.
This means that, in jumping back to before the declaration, you jump to a stack frame situations where the local didn't exist, so it must be destructed
The
point of declaration
for a name is immediately after its complete declarator (Clause 8) and before its initializer (if any) , [...] (§ 3.3.2)
A name declared in a block (6.3) is local to that block; it has block scope. Its potential scope begins at its point of declaration (3.3.2) and ends at the end of its block. A variable declared at block scope is a local variable. (§ 3.3.3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With