(全局)静态变量会在程序结束时销毁吗? [英] Will (global) static variables be destroyed at program end?

查看:444
本文介绍了(全局)静态变量会在程序结束时销毁吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
C ++是否为全局和类静态变量调用析构函数? /a>

Possible Duplicate:
Does C++ call destructors for global and class static variables?

什么是寿命

  • 全局MyClass myclass;
  • 全局static MyClass myclass;
  • 全局const MyClass myclass;
  • 全局static const MyClass myclass;
  • 功能本地static MyClass myclass;何时实际发生初始化
  • C ++ 11中的
  • 全局static constexpr MyClass myclass;
  • global MyClass myclass;
  • global static MyClass myclass;
  • global const MyClass myclass;
  • global static const MyClass myclass;
  • function local static MyClass myclass; when its initialization actually occured
  • global static constexpr MyClass myclass; in C++11

,尤其是是否会在常规程序结束时将其销毁(即main不会出现错误)?标准在哪里规定?

and especially will they be destroyed on regular program end (i.e. main is left without an error)? Where does the standard states so.

我注意到私有析构函数阻止了所有这些变量的创建.但是,如果我没记错的话,在某处明确提到了一些静态数据可能已经放入静态数据段中并已经预先构建的加载了.对我而言,这意味着不会调用任何析构函数.这意味着我可以定义这样的变量...

I noticed that a private destructor prevents the creation of all those variables. But if I remember correctly it was explicitly mentioned somewhere that some static data may be put into a static data section and loaded pre-constructed, already. This would imply for me that no destructor would be called. And this would imply I am allowed to define such a variable...

推荐答案

当控制流离开main()时,将调用文件或名称空间作用域对象的析构函数.

The destructors of file or namespace scope objects get called when the control flow leaves main().

如果异常离开main(),则其实现定义是否调用任何对象的析构函数.对于现代编译器,在这种情况下将不会调用析构函数,以在抛出未处理的异常时轻松检查程序状态.早期的C ++实现使用基于setjmp/longjmp的异常机制,该机制将在搜索异常处理程序时展开堆栈,从而即使最终找不到合适的异常处理程序也将调用析构函数.

If an exception leaves main() then it's implementation defined whether the destructors of any objects get called. With modern compilers the destructors won't be called in this case to allow easy inspection of the program state when the unhandled exception was thrown. Early C++ implementations used exception mechanism based on setjmp/longjmp which would unwind the stack while searching for the exception handler and hence calling destructors even if no suitable exception handler was eventually found.

如果应用程序以_exit()_Exit()std::quick_exit()终止,则不会调用任何析构函数.

If an application terminates with _exit() or _Exit() or std::quick_exit() no destructors get called.

这篇关于(全局)静态变量会在程序结束时销毁吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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