具有静态存储持续时间的对象的销毁

编程入门 行业动态 更新时间:2024-10-23 22:31:33
本文介绍了具有静态存储持续时间的对象的销毁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

请考虑以下程序.

struct s { ~s(); }; void f() { static s a; } struct t { ~t() { f(); } }; int main() { static s b; static t c; }

我试图弄清楚标准对于销毁静态对象的确切保证,但是我发现C ++ 03 [basic.start.term]的文字还不够.

I'm trying to figure out what exactly the standard guarantees with respect to the destruction of static objects, but I'm finding the text of C++03[basic.start.term] rather insufficient.

程序的行为是否已定义?如果是这样,销毁静态对象 a , b 和 c 的顺序是什么?如果 s ::〜s 抛出异常会怎样?请解释您的理由,最好使用标准中的引号.

Is the behavior of the program defined? If so, what is the order of destruction of the static objects a, b and c? What would happen if s::~s threw an exception? Please explain your reasoning, preferably with quotes from the standard.

推荐答案

在下面的 Objects 中,指的是静态存储持续时间的对象.

In the following Objects refers to objects of static storage duration.

全局名称空间中的对象是在main之前创建的.

Objects in the global namespace are created before main.

同一编译单元中的对象按定义顺序创建.在不同的编译单元中未定义顺序.

Objects in the same compilation unit are created in order of definition. The order is undefined across different compilation units.

在访问该名称空间中的任何函数/变量之前,先创建该名称空间中的对象.这可能在main之前,也可能不在.

Objects in a namespace are created before any function/variable in that namespace is accessed. This may or may not be before main.

函数中的对象是在首次使用时创建的.

Objects in a function are created on first use.

对象以相反的创建顺序销毁.请注意,创建的顺序由其CONSTRUCTOR的完成定义(而不是在调用时).因此,一个在其构造函数中创建另一个"y"的对象"x"将导致首先构造"y".

Objects are destroyed in reverse order of creation. Note the order of creation is defined by the completion of their CONSTRUCTOR (not when it was called). Thus one object 'x' that creates another 'y' in its constructor will result in 'y' being constructed first.

如果未创建它们,则它们将不会被破坏.

If they were not created then they will not be destroyed.

程序的行为是否已定义?

Is the behavior of the program defined?

是的,订单定义明确

b: Created c: Created c: Destroyed Start a: Created (during destruction of C) c: Destroyed End a: Destroyed (a was created after b -> destroyed before b) b: Destroyed

修改代码以查看:

#include <iostream> struct s { int mx; s(int x): mx(x) {std::cout << "S(" << mx << ")\n";} ~s() {std::cout << "~S(" << mx << ")\n";} }; void f() { static s a(3); } struct t { int mx; t(int x): mx(x) { std::cout << "T(" << mx << ")\n";} ~t() { std::cout << "START ~T(" << mx << ")\n"; f(); std::cout << "END ~T(" << mx << ")\n"; } }; int main() { static s b(1); static t c(2); }

输出为:

$ ./a.exe S(1) T(2) Start ~T(2) S(3) END ~T(2) ~S(3) ~S(1)

更多推荐

具有静态存储持续时间的对象的销毁

本文发布于:2023-10-27 15:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533806.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   持续时间   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!