C++ Builder 參考手冊 ? <cstdlib> ? atexit
頭文件:#include <cstdlib>
命名空間:std
函數(shù)原型:
int atexit(void (_USERENTRY *func)(void));
參數(shù):
func:要添加的在程序退出時運行的函數(shù),這個參數(shù)是 atexit_t 類型的函數(shù)指針,即沒有參數(shù)和返回值的,_USERENTRY 調(diào)用約定的函數(shù)。
返回值:
0:成功,非0:失敗,添加的函數(shù)超過了 32 個。
- 添加一個在程序退出時運行的函數(shù),先添加的后執(zhí)行,后添加的先執(zhí)行;
- 最多能添加 32 個這樣的函數(shù);
- 程序正常退出時,執(zhí)行的順序:
? std::atexit 添加的函數(shù),先添加的后執(zhí)行,后添加的先執(zhí)行;
? #pragma exit 添加的函數(shù),按照優(yōu)先級,或者 #pragma package(smart_init) 的控制;
? 全局變量的析構(gòu)函數(shù)。
例1:
void _USERENTRY Func1(void)
{
ShowMessage(L"正在執(zhí)行函數(shù) Func1");
}
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
std::atexit(Func1);
}
運行結(jié)果:

運行結(jié)果:當程序退出時,彈出對話框:“正在執(zhí)行函數(shù) Func1”
例2:
#include <cstdlib>
#include <iostream>
using namespace std;
void _USERENTRY Func1(void)
{
cout << "Func1" << endl;
}
void _USERENTRY Func2(void)
{
cout << "Func2" << endl;
}
int main(void)
{
atexit(Func1);
atexit(Func2);
cout << "Test std::atexit - Hsuanlu" << endl;
return 0;
}
運行結(jié)果:

運行結(jié)果:程序退出時,先添加的后執(zhí)行,后添加的先執(zhí)行
相關(guān):
- std::atexit_t
- std::exit
- std::abort
- std::_Exit
- System::Sysutils::AddExitProc
- System::Sysutils::TProcedure
- System::Sysutils::AddTerminateProc
- System::Sysutils::TTerminateProc
- System::Sysutils
- <cstdlib>
C++ Builder 參考手冊 ? <cstdlib> ? atexit