Use of setjmp and longjmp in C when linking to C++ libraries

拥有回忆 提交于 2019-12-23 09:17:47

问题


I would like to use setjmp and longjmp in a C program that links to a library that is implemented in C++ (but has a C API).

The C++ code does do dynamic memory allocation and pointers get passed through the API, but as long as the C side of the code manages those (opaque) objects correctly, there shouldn't be any messing up when using longjmp, right?

I know it's not safe to use these functions in C++ code, but should it be safe in C code that is linked to C++ code?


回答1:


The fact that you call C++ functions from your C code does not make setjmp and longjmp more unsafe than they always are.

What's important is that if your library allocates resources you must have recovery code in place to ensure that those are released properly after longjmp is called. While this is likely easy for your own allocations, it may be hard or impossible for the C++ library depending on how the C interface you use is structured.




回答2:


setjmp/longjmp are, in general, not safe for use with C++. They effectively replicate the behavior of exceptions, but without unwinding the stack correctly (for instance, they will not run destructors for objects on stack frames that they forcibly exit). Where possible, use exceptions instead if you've got them.




回答3:


Well, right and not right. longjmp will in general not call destructors, so using it in a code like the following:

void f(jmp_buf jb)
{
  some_cpp_object_with_a_nontrivial_destructor x;
  if (some_condition) longjmp(jb, 2);
  // some other code
}

will make all sorts of bad things happen. If you avoid such situations, you should be OK. (In general, longjmp must not jump across any active stack frames with objects having non-trivial destructors.)



来源:https://stackoverflow.com/questions/7252455/use-of-setjmp-and-longjmp-in-c-when-linking-to-c-libraries

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