Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

goto and RAII in C++ [duplicate]

Tags:

c++

goto

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.

like image 213
FrozenHeart Avatar asked Aug 27 '12 20:08

FrozenHeart


1 Answers

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).

n3376

6.6 Jump statments: [stmt.jump]

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 ]

like image 137
Mankarse Avatar answered Sep 28 '22 01:09

Mankarse