函数setjmp()的行为:
直接调用,将所有与当前处理器相关的信息(比如指令指针的内容、运行时栈指针等)保存到jmp_buf中去并返回0,表现的像一个普通函数。
如果使用同一个jmp_buf调用longjmp(),则函数返回时又回到了刚刚从setjmp()返回的地方。这一次函数的返回值是调用longjmp()时所使用的第二个参数。注意,第二个参数不能为零。如果为零,则setjmp()的返回值将为1,而不是零。
示例代码如下:
#include "stdafx.h"
#include <iostream>
#include <csetjmp>
using namespace std;
class Rainbow
{
public:
Rainbow(){cout << "Rainbow()" << endl;}
~Rainbow(){cout << "~Rainbow()" << endl;}
};
jmp_buf kansas;
void oz()
{
Rainbow rb;
for (int i = 0; i < 3; i++)
{
cout << "There is no place like home" << endl;
}
longjmp(kansas,1);
}
int _tmain(int argc, _TCHAR* argv[])
{
int rtn = setjmp(kansas);
if (rtn == 0)
{
cout << "北京, 上海, 武汉, 广州 ..." << endl;
oz();
}
else if(rtn == 1)
{
cout << "我爱看"
<< "Thinking In C++"
<< endl;
}
return 0;
}
#include <iostream>
#include <csetjmp>
using namespace std;
class Rainbow
{
public:
Rainbow(){cout << "Rainbow()" << endl;}
~Rainbow(){cout << "~Rainbow()" << endl;}
};
jmp_buf kansas;
void oz()
{
Rainbow rb;
for (int i = 0; i < 3; i++)
{
cout << "There is no place like home" << endl;
}
longjmp(kansas,1);
}
int _tmain(int argc, _TCHAR* argv[])
{
int rtn = setjmp(kansas);
if (rtn == 0)
{
cout << "北京, 上海, 武汉, 广州 ..." << endl;
oz();
}
else if(rtn == 1)
{
cout << "我爱看"
<< "Thinking In C++"
<< endl;
}
return 0;
}