C++中_onexit()用法简述

2015-07-20 17:53:54 · 作者: · 浏览: 4
引问:main 主函数执行完毕后,是否可能会再执行一段代码?

答案:可以,可以用_onexit 注册一个函数,它会在main 之后执行。

知识了解:

(1)使用格式:_onexit(int fun()) ,其中函数fun()必须是带有int类型返回值的无参数函数;

(2)_onexit() 包含在头文件cstdlib中,cstdlib为c语言中的库函数;

(3)无论函数_onexit() 放到main中任意位置,它都是最后执行。

程序举例分析:

#include
#include
using namespace std;


int func1(),func2(),func3();

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

_onexit(func2);
_onexit(func1); //在此处不断排列组合三条语句的执行顺序
_onexit(func3);
cout<<"First Line"< cout<<"Second Line"< }

int func1()
{
cout<<"fun1() executed!"< return 0;
}

int func2()
{
cout<<"fun2() executed!"< return 0;
}
int func3()
{
cout<<"fun3() executed!"< return 0;
}


根据多次重新排列组合 _onexit(func2); _onexit(func1); _onexit(func3);的执行顺序可知:_onexit()在main()中越靠后,则其执行顺序越靠前;即越在前面的就越延后执行,有点类似‘栈’(先进后出)的特点。


ps:由于作者技术水平有限,如有错误和不恰当之处,还望读者不吝赐教!