I'd just like to answer the other part of the question, by speculating why NASA would forbid these functions (basically linking relevant answers from SO). The use of setjmp
and longjmp
are discouraged in C++ more so than in C code, due to undefined behavior regarding automatic object destruction, see this SO thread, particularly the comments to the accepted answer:
Generally, whenever there's some way to exit a scope in C++ (return, throw, or whatever), the compiler will place instructions to call the dtors for any automatic variables that need to be destroyed as a result of leaving that block. longjmp()
just jumps to a new location in the code, so it will not provide any chance for the dtors to be called. The standard is actually less specific than that - the standard doesn't say that dtors won't be called - it says that all bets are off. You can't depend on any particular behavior in this case.
[...]
Since smart pointers depend on being destroyed, you will get undefined behavior. It's likely that that undefined behavior would include a refcount not getting decremented. You're 'safe' using longjmp()
as long as you don't longjmp out of code that should cause dtors to be invoked. However, as David Thornley noted in a comment, setjmp()
/longjmp()
can be tricky to use right even in straight C - in C++ they're downright dangerous. Avoid them if at all possible.
So what makes the setjmp()
/longjmp()
tricky in C? Look at possible use cases we can see that one of them is implementation of coroutines. The answer was already given here in the comments @StoryTeler, but could you use goto
across different functions?
You can't in Standard C; labels are local to a single function.
The nearest standard equivalent is the setjmp() and longjmp() pair of functions.
However, you're quite limited with setjmp
and longjmp
as well, and you might quickly run into a segfault. The treasure can again be found in the comments:
You can think of a longjmp()
as an "extended return". A successful longjmp()
works like a series of successive returns, unwinding the call stack until it reaches the corresponding setjmp()
. Once the call stack frames are unwound, they are no longer valid. This is in contrast to implementations of coroutines (eg. Modula-2) or continuations (eg. Scheme) where the call stack remains valid after jumping somewhere else. C and C++ only support a single linear call stack, unless you use threads where you create multiple independent call stacks.