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


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

C++ 中的atexit() 函數注冊了一個在正常程序終止時調用的函數。

C++ 中的atexit() 函數注冊了一個在正常程序終止時調用的函數。

atexit()原型

extern int atexit (void (*func)(void));

該函數在<cstdlib> 頭文件中定義。

參數:

  • func:指向在正常程序終止時調用的函數的指針。

返回:

atexit() 函數返回:

  • 如果函數注冊成功,則為零。
  • 如果函數注冊失敗,則非零。

示例 1:atexit() 函數如何工作?

#include <iostream>
#include <cstdlib>
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 函數,則按相反的順序執行,即先執行 atlast 注冊的函數。可以多次注冊相同的函數。

可以使用atexit() 注冊的函數調用的數量取決於特定的庫實現。但是,最低限製是 32。

示例 2:使用atexit() 注冊多個函數

#include <iostream>
#include <cstdlib>
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() 函數。

示例 3:atexit() 函數拋出未處理的異常

#include <iostream>
#include <cstdlib>
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

相關用法


注:本文由純淨天空篩選整理自 C++ atexit()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。