views:

96

answers:

2

I was under the impression that using setjmp() and longjmp() in C++ was almost guaranteed to mess up the stack, since these functions don't perform unwinding like, say, exceptions do. This MSDN page, however, indicates that the Microsoft implementation can be told to invoke the destructors of local objects, which implies that careful use of these functions could be safe.

Is there a portable means of ensuring program correctness when using setjmp() and longjmp() in C++? Best practices in C++ indicate that exceptions are best not used for flow control, but in a situation that requires highly unusual flow (e.g., coroutines and closures), is it always preferable to use exceptions in lieu of these functions?

+1  A: 

If you have some really weird requirement that doesn't allow you to control the flow of the program normally, with conditionals/loops/breaks, I would prefer to use an exception over jmp.

There are scenarios where using an exception to control flow is acceptable. I think one of Boost.Graph's search functions throws an exception to quickly return to the caller from deep recursion.

dauphic
Well, then, I'll prefer exceptions. I'd still like to know whether it's *possible* to get away with `*jmp()`, though.
Jon Purdy
No, it's not possible to do it while retaining portability. I just tested on Windows with Visual Studio and Linux with gcc. The VS implementation called destructors correctly. The gcc implementation didn't destruct objects that were removed from the stack.
dauphic
I had the case where I was creating a wrapper around an old C library (don't remember which one) ; this library required me to pass callback functions, and some parts of that library (that I called inside the callbacks) where using longjmp. This is the kind of code I hope I'll never have to debug
Tomaka17
@dauphic: Thanks!
Jon Purdy
+1  A: 

I've used them before, but only under one circumstance: I was creating an OS kernel in C for an OS class; they were used for exception handling.

My understanding is that they're used for exception handling when dealing with low-level code, like an operating system. For general C++ software, I'd just use try catch.

Jesse J