开发者

Is there a safe way to use setjmp() and longjmp() in C++?

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 contro开发者_如何学JAVAl, 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜