C++: Safe to use longjmp and setjmp?

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-26 08:16:54

问题


Is it safe to use longjmp and setjmp in C++ on linux/gcc with regards to the following?

  1. Exception handling (I\'m not implementing exception handling using longjmp/setjmp. I want to know what side effects longjmp/setjmp will have on standard exception handling)
  2. *this pointer
  3. Signals
  4. Smart pointers (boost\'s shared and intrusive pointers)
  5. Anything else you can think of.

回答1:


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++.




回答2:


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.



来源:https://stackoverflow.com/questions/1376085/c-safe-to-use-longjmp-and-setjmp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!