当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ atexit()用法及代码示例


当程序正常终止时,将自动调用atexit()指向的函数,而无需使用参数。如果通过对该函数的不同调用指定了多个atexit函数,则所有函数均按堆栈顺序执行(即,指定的最后一个函数是在退出时第一个执行的函数)。可以注册一个函数以在退出处执行一次以上。

用法:

extern "C" int atexit (void (*func)(void)) noexcept;
extern "C++" int atexit (void (*func)(void)) noexcept

注意: extern是指该名称将引用整个程序中的同一对象。


参数:该函数接受一个强制性参数fun,该参数指定在正常程序终止时要调用的函数的指针(要调用的函数)。

返回值:该函数返回两个值:

  • 零,如果函数注册成功
  • 非零,如果函数注册失败

以下示例程序旨在说明上述函数:

程序1:

// C++ program to illusttrate 
// atexit() function 
#include <bits/stdc++.h> 
using namespace std; 
  
// Returns no value, and takes nothing as a parameter 
void done() 
{ 
    cout << "Exiting Successfully"
         << "\n"; // Executed second 
} 
// Driver Code 
int main() 
{ 
    int value; 
    value = atexit(done); 
  
    if (value != 0) { 
        cout << "atexit () function registration failed"; 
        exit(1); 
    } 
    cout << " Registration successful"
         << "\n"; // Executed First 
    return 0; 
}
输出:
Registration successful
Exiting Successfully

如果在主函数中调用了多个atexit函数,则所有指定函数将以相反的方式执行,与堆栈的函数相同。

程序2:

// C++ program to illustrate 
// more than one atexit function 
#include <bits/stdc++.h> 
using namespace std; 
  
// Executed last, in a Reverse manner 
void first() 
{ 
    cout << "Exit first" << endl; 
} 
  
// Executed third 
void second() 
{ 
    cout << "Exit Second" << endl; 
} 
  
// Executed Second 
void third() 
{ 
    cout << "Exit Third" << endl; 
} 
  
// Executed first 
void fourth() 
{ 
    cout << "Exit Fourth" << endl; 
} 
// Driver Code 
int main() 
{ 
    int value1, value2, value3, value4; 
    value1 = atexit(first); 
    value2 = atexit(second); 
    value3 = atexit(third); 
    value4 = atexit(fourth); 
    if ((value1 != 0) or (value2 != 0) or 
        (value3 != 0) or (value4 != 0)) { 
        cout << "atexit() function registration Failed" << endl; 
        exit(1); 
    } 
    // Executed at the starting 
    cout << "Registration successful" << endl; 
    return 0; 
}
输出:
Registration successful
Exit Fourth
Exit Third
Exit Second
Exit first

程序3:

// C++ program to illustrate 
// atexit() function when it throws an exception. 
#include <bits/stdc++.h> 
using namespace std; 
  
void shows_Exception() 
{ 
    int y = 50, z = 0; 
    // Program will terminate here 
    int x = y / z; 
  
    // Cannot get printed as the program 
    // has terminated 
    cout << "Divided by zero"; 
} 
// Driver Code 
int main() 
{ 
    int value; 
    value = atexit(shows_Exception); 
    if (value != 0) { 
        cout << "atexit() function registration failed"; 
        exit(1); 
    } 
  
    // Executed at the starting 
    cout << "Registration successful" << endl; 
    return 0; 
}

注意:如果已注册的函数引发了无法处理的异常,则将调用terminate()函数。



相关用法


注:本文由纯净天空筛选整理自AmanSrivastava1大神的英文原创作品 atexit() function in C/C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。