Possible Duplicate:
Goto out of a block: do destructors get called?
I know that goto operator both in C and C++ is useless in almost all situations, but i want to know the answer for this question only by interest, it has no practical meaning.
Does C++ standard guarantees that in such situations destructors of objects must be called properly?
#include <iostream>
class Foo
{
public:
Foo() { std::cout << "Foo::Foo() \n"; }
~Foo() { std::cout << "Foo::~Foo() \n"; }
};
int main()
{
{
std::size_t i = 0;
_1:
Foo instance;
if (!++i)
{
goto _1;
}
}
{
Foo instance;
goto _2;
}
_2:
;
}
http://liveworkspace.org/code/06031e6699c8fddda94b8594ccab1387
And what about other stange situations with goto and C++ RAII?
It would be really cool if you can post here the quotes from the C++ standard.
Yes. Automatic objects are guaranteed to be destructed when they go out of scope. The fact that the scope was exited using goto
has no effect on this rule.
The only situation that I can think of where this doesn't hold is if the scope is exited using std::longjmp (in which case behaviour is undefined if there are any objects with destructors).
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 ]
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