📅  最后修改于: 2020-09-25 08:45:46             🧑  作者: Mango
C++中的atexit() 函数注册一个在正常程序终止时要调用的函数 。
extern int atexit (void (*func)(void));
此函数在
atexit() 函数返回:
#include
#include
using namespace std;
void bye()
{
cout << "Program Exiting Successfully";
}
int main()
{
int x;
x = atexit(bye);
if (x != 0)
{
cout << "Registration Failed";
exit(1);
}
cout << "Registration successful" << endl;
return 0;
}
运行该程序时,输出为:
Registration successful
Program Exiting Successfully
可以注册多个函数以在终止时执行。
如果注册了多个atexit功能,则以相反的顺序执行它们,即,首先执行最后注册的函数 。相同函数可以多次注册。
可以使用atexit()注册的函数调用的数量取决于特定的库实现。但是,最小限制为32。
#include
#include
using namespace std;
void exit1()
{
cout << "Exit Function 1" << endl;
}
void exit2()
{
cout << "Exit Function 2" << endl;
}
void exit3()
{
cout << "Exit Function 3" << endl;
}
int main()
{
int x1, x2, x3;
/* Executed at last*/
x1 = atexit(exit1);
x2 = atexit(exit2);
/* Executed at first */
x3 = atexit(exit3);
if ((x1 != 0) or (x2 != 0) or (x3 != 0))
{
cout << "Registration Failed";
exit(1);
}
cout << "Registration successful" << endl;
return 0;
}
运行该程序时,输出为:
Registration successful
Exit Function 3
Exit Function 2
Exit Function 1
如果在终止时调用已注册的函数引发未处理的异常,则会调用Terminate() 函数 。
#include
#include
using namespace std;
void bye()
{
cout << "Generates Exception";
int a = 5, b = 0;
int x = a/b;
/* Program will terminate here */
cout << "Division by zero";
}
int main()
{
int x;
x = atexit(bye);
if (x != 0)
{
cout << "Registration Failed";
exit(1);
}
cout << "Registration successful" << endl;
return 0;
}
运行该程序时,输出为:
Registration successful
Generates Exception