原理:
使用 _onexit() 函数注册一个函数,这个函数会在main函数退出后执行
使用原则:
1、包含在cstdlib中,是c语言中的库函数;
2、需要注册的函数格式为:int类型返回值、无参数,参见_onexit()定义;
3、无论_onexit函数放到main中哪个位置,相应的已注册函数都是最后执行;
4、如果用_onexit注册了多个函数, 则已注册函数的执行顺序跟注册顺序相反;
测试代码:
1 #include "stdafx.h" 2 #include <iostream> 3 #include <cstdlib> 4 5 using namespace std; 6 7 8 int test1( int nV1, int nV2 ) 9 { 10 cout << "in test1()" << endl; 11 return nV1+nV2; 12 } 13 14 int fun1() 15 { 16 cout << "excute fun1" << endl; 17 return 0; 18 } 19 20 int fun2() 21 { 22 cout << "excute fun2" << endl; 23 return 0; 24 } 25 26 int main(int argc, char* argv[]) 27 { 28 //_onexit(test1); //error C2664: '_onexit' : cannot convert parameter 1 from 'int (int,int)' to 'int (__cdecl *)(void)' 29 30 _onexit(fun1); 31 32 cout << "exit" << endl; 33 34 _onexit(fun2); 35 36 return 0; 37 }
输出结果:
exit
excute fun2
excute fun1