1

如何在程序退出时运行函数

 2 years ago
source link: https://charon-cheung.github.io/2022/08/31/C++/C++%20%20%E5%9F%BA%E7%A1%80/%E5%A6%82%E4%BD%95%E5%9C%A8%E7%A8%8B%E5%BA%8F%E9%80%80%E5%87%BA%E6%97%B6%E8%BF%90%E8%A1%8C%E5%87%BD%E6%95%B0/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

如何在程序退出时运行函数 | 沉默杀手

如何在程序退出时运行函数
2022-08-31|C++C++ 基础|
Word count: 252|Reading time: 1 min

很多时候我们需要在程序退出的时候做一些诸如释放资源的操作,但程序退出的方式有很多种,比如main()函数运行结束、在程序的某个地方用exit()结束程序、用户通过Ctrl+C或Ctrl+break操作来终止程序等等,因此需要有一种与程序退出方式无关的方法,在退出时执行某函数。方法就是用atexit()函数来注册程序正常终止时要被调用的函数。

#include <cstdlib>

void atexit_handler_1()
{
std::cout << "at exit #1\n";
}

void atexit_handler_2()
{
std::cout << "at exit #2\n";
}

QApplication a(argc, argv);

const int result_1 = std::atexit(atexit_handler_1);
const int result_2 = std::atexit(atexit_handler_2);

if ((result_1 != 0) || (result_2 != 0)) {
std::cerr << "Registration failed\n";
return EXIT_FAILURE;
}
MainWindow w;
w.show();
return a.exec();

atexit执行成功,返回0,否则返回非0.

当程序正常终止(调用exit()或者由main函数返回)时,调用atexit()参数中指定的函数。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK