在jpeglib中,必须使用 setjmp/longjmp 来实现自定义错误处理。
有很多资源说 setjmp/longjmp 不能很好地与 c++ 配合使用(例如,这个问题中的答案告诉他们确实与 RAII 一起使用),但是这个问题的答案说调用了析构函数。
我有这个例子(取自这里并稍作修改):
#include <iostream>
#include <csetjmp>
std::jmp_buf jump_buffer;
struct A
{
A(){std::cout<<"A()"<<std::endl;}
~A(){std::cout<<"~A()"<<std::endl;}
};
void a(int count)
{
std::cout << "a(" << count << ") called\n";
std::longjmp(jump_buffer, count+1); // setjump() will return count+1
}
int main()
{
// is this object safely destroyed?
A obj;
int count = setjmp(jump_buffer);
if (count != 9) {
a(count);
}
}
在这个例子中,析构函数被调用(如我所料),但它是标准行为吗?还是编译器的扩展,还是简单的 UB?
输出:
A()
a(0) called
a(1) called
a(2) called
a(3) called
a(4) called
a(5) called
a(6) called
a(7) called
a(8) called
~A()