如何在C ++的退出运行一个函数 [英] How do you run a function on exit in C++

查看:422
本文介绍了如何在C ++的退出运行一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,我想要运行,当我的程序退出:

I have a function that I want to run whenever my program exits:

void foo() {
  std::cout<< "Exiting" << std::endl;
}

如果注册程序存在,

推荐答案

您可以使用适当命名的 std :: atexit 函数在 cstdlib 标题:

You can use the aptly named std::atexit function in the cstdlib header:

#include <cstdlib>

void exiting() {
    std::cout << "Exiting";
}

int main() {
    std::atexit(exiting);
}

系统将维护一堆注册到 atexit ,并在调用 exit 函数时,以它们的注册顺序调用它们,或者程序从 main 。您可以用这种方式注册至少32个功能。

The system will maintain a stack of functions registered with atexit and call them each in the reverse order of their registration when either the exit function is called, or the program returns from main. You can register at least 32 functions this way.

这篇关于如何在C ++的退出运行一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆