Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does computed `goto` respect C++ object lifetime?

Tags:

c++

gcc

raii

goto

Regular goto in C++ respects object lifetime - that is using goto to jump out of a block will run the destructors for the appropriate local variables.

start:
NonTrivial object;
if (again()) goto start;  // will call object.~NonTrivial()

Is the same true when using the Labels as Values extension?

start:
NonTrivial object;
goto *(again() ? &&start : &&end);
end:

GCC happily accepts this code, but seems to ignore any effect goto might have on object's lifetime. Clang complains:

error: cannot jump from this indirect goto statement to one of its possible targets
note: possible target of indirect goto statement
note: jump exits scope of variable with non-trivial destructor   

Look for calls to NonTrivial() and ~NonTrivial() in Compiler Explorer.

Which compiler behaves correctly? Is it even possible, in general, to support this kind of indirect branching and also correctly manage object lifetime and RAII?

like image 440
Filipp Avatar asked Nov 07 '22 08:11

Filipp


1 Answers

Which compiler behaves correctly?

Since we are talking about language extension by GCC, we cannot use C++ standard for the judgement. But it is reasonable to expect that the compiler will call here destructor automatically the same number of times as constructor, or refuse to compile as Clang.

Is it even possible, in general, to support this kind of indirect branching and also correctly manage object lifetime and RAII?

Probably yes, since GCC bug for this is reported and not closed yet: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=37722

like image 118
Fedor Avatar answered Nov 15 '22 06:11

Fedor