本文主要介绍c/c++程序在main函数运行结束时如果需要做类似于释放内存等操作的话,可以通过在main函数中调用atexit()函数注册相对应的回调函数(类型为void (*)(void)注册的最大个数是32个),在main函数最后退出的时候,就会按照回调函数注册的相反顺序,执行回调函数中的程序。
如下的代码示例:
#include "stdafx.h"
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#pragma warning(disable:4996)
using namespace std;
void fun1(void)
{
cout << "fun1 is called" << endl;
}
void fun2(void)
{
cout << "fun2 is called" << endl;
}
int main(int argc, char *argv[])
{
int a = 10;
int b = 20;
atexit(fun1);
atexit(fun2);
cout << "main is exit!!!" << endl;
return 0;
}
下面的测试结果也证明了这个用法:

本文详细介绍了如何在C/C++程序中使用atexit函数来注册回调函数,以便在main函数结束时执行资源清理操作,如释放内存。通过示例代码展示了回调函数的注册与执行顺序。

2019

被折叠的 条评论
为什么被折叠?



