atexit函数
C ++ atexit()函数 (C++ atexit() function)
atexit() function is a library function of cstdlib header. It is used to set a function that should be executed on exit. Sometimes we need to write such code (like freeing the memory occupied by the global variables, closing the file objects, etc) that should be executed when the program is going to exit, any user-defined can be written for it and that can be set as an exit function using atexit() function.
atexit()函数是cstdlib标头的库函数。 它用于设置退出时应执行的功能。 有时我们需要编写这样的代码(例如释放由全局变量占用的内存,关闭文件对象等),这些代码应在程序退出时执行,可以为其编写任何用户定义的代码,并且可以使用atexit()函数设置为退出函数 。
The function invokes automatically when the program terminates normally. The function should be a void type.
当程序正常终止时,该函数自动调用。 该函数应为void类型。
Syntax of atexit() function:
atexit()函数的语法:
C++11:
C ++ 11:
extern "C" int atexit (void (*func)(void)) noexcept;
extern "C++" int atexit (void (*func)(void)) noexcept;
Parameter(s):
参数:
func – represents the function to be called at program exit.
func –表示要在程序退出时调用的函数。
Return value:
返回值:
The return type of this function is int, it returns 0 if the function registered successfully; non-zero, otherwise.
该函数的返回类型为int ,如果该函数成功注册,则返回0;否则返回0。 非零,否则。
Example:
例:
// defining the function
void function_name(void){
// function code
}
// setting the function
atexit(function_name);
C ++代码演示atexit()函数的示例 (C++ code to demonstrate the example of atexit() function)
// C++ code to demonstrate the example of
// atexit() function
#include <iostream>
#include <cstdlib>
using namespace std;
void function1(void)
{
cout << "Bye, Bye..." << endl;
}
void function2(void)
{
cout << "Tata, Tata..." << endl;
}
// main() section
int main()
{
//setting the functions
atexit(function1);
atexit(function2);
cout << "Hi, friends..." << endl;
cout << "Input first number: ";
int a;
cin >> a;
cout << "Input second number: ";
int b;
cin >> b;
cout << a << "+" << b << " = " << a + b << endl;
return 0;
}
Output
输出量
Hi, friends...
Input first number: 10
Input second number: 20
10+20 = 30
Tata, Tata...
Bye, Bye...
Reference: C++ atexit() function
参考: C ++ atexit()函数
翻译自: https://www.includehelp.com/cpp-tutorial/atexit-function-with-example.aspx
atexit函数