Post

C++ 程序结束时运行

std::atexit 可以加载函数,使其在程序结束时运行。

如果std::atexit出现多次,则对应函数也会执行多次。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <cstdlib>

void cleanup() {
	std::cout << "清理资源..." << std::endl;
	// 在这里添加清理代码
}

int main() {
	std::atexit(cleanup);
	std::atexit(cleanup);
	std::cout << "程序正在运行..." << std::endl;
	return 0;
}
This post is licensed under CC BY 4.0 by the author.