Reputation: 7301
Is it safe to use longjmp and setjmp in C++ on linux/gcc with regards to the following?
*this
pointerUpvotes: 46
Views: 16327
Reputation: 340188
setjmp()
/longjmp()
completely subvert stack unwinding and therefore exception handling as well as RAII (destructors in general).
From 18.7/4 "Other runtime support" in the standard:
If any automatic objects would be destroyed by a thrown exception transferring control to another (destination) point in the program, then a call to
longjmp(jbuf, val)
at the throw point that transfers control to the same (destination) point has undefined behavior.
So the bottom line is that setjmp()
/longjmp()
do not play well in C++.
Upvotes: 66
Reputation: 63538
It's not specific to Linux or gcc; setjmp / longjmp and C++ don't work too well together if you're using longjmp to leave a context where there are automatic variables with destructors.
The destructors won't run which may result in a memory leak or other bad behaviour.
Upvotes: 6