當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。