问题与longjmp

ang*_*ela 1 c++ longjmp

我想使用longjmp来模拟goto指令.我有一个包含struct类型元素的数组DS(int,float,bool,char).我想跳到标有"lablex"的地方,其中x是DS [TOP] .int_val.我怎么处理这个?

示例代码:

...
jmp_buf *bfj;
...
stringstream s;s<<"label"<<DS[TOP].int_val;
bfj = (jmp_buf *) s.str();
longjmp(*bfj,1);
Run Code Online (Sandbox Code Playgroud)

但是我认为它有问题我该怎么办?

错误:

output.cpp:在函数'int main()'中:

output.cpp:101:错误:从类型'std :: basic_string,std :: allocator>'转换为无效的类型'__jmp_buf_tag(*)[1]'

ste*_*anv 5

使用跳远踏板的正常方式是incombination与setjump()所描述的在这里.您似乎想像通常使用switch-case或虚函数一样进行跳转.

无论如何,代码(编译时)中的标签不能用字符串(运行时)访问,所以这已经是你的第一个问题了.你真的需要找到你想要跳转到的地址,我最好的猜测是将setjump()放在你的标签所在的位置.


jco*_*and 5

你可能根本不想使用longjmp,但是当人们回答"你为什么要这样做?"的问题时我讨厌它.正如已经指出你的longjmp()用法是错误的.这是一个如何正确使用它的简单示例:

#include <setjmp.h>

#include <iostream>

using namespace std;

jmp_buf jumpBuffer;  // Declared globally but could also be in a class.

void a(int count) {
  // . . .
  cout << "In a(" << count << ") before jump" << endl;
  // Calling longjmp() here is OK because it is above setjmp() on the call
  //   stack.
  longjmp(jumpBuffer, count);  // setjump() will return count
  // . . .
}


void b() {
  int count = 0;

  cout << "Setting jump point" << endl;
  if (setjmp(jumpBuffer) == 9) return;
  cout << "After jump point" << endl;

  a(count++);  // This will loop 10 times.
}


int main(int argc, char *argv[]) {
  b();

  // Note: You cannot call longjmp() here because it is below the setjmp() call
  //  on the call stack.

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

您使用longjmp()的问题如下:

  1. 你不要调用setjmp()
  2. 您尚未在堆栈上或动态分配jmp_buf. jmp_buf*bfj只是一个指针.
  3. 你不能将char*转换jmp_buf*并期望它能够工作.C++不是静态编译的动态语言.

但实际上,你根本不可能使用longjmp().

  • 只是重申 - 因为我认为这是OP缺失的要点 - 要做一个`longjmp`你首先必须要`setjmp`.换句话说,你_notnot_跳到你以前没去过的地方. (7认同)