具有静态存储持续时间的对象的销毁 [英] Destruction of objects with static storage duration

查看:66
本文介绍了具有静态存储持续时间的对象的销毁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下程序.

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)

这篇关于具有静态存储持续时间的对象的销毁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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