为什么通过goto向后退时调用析构函数 [英] Why destructor is called when going backward via goto

查看:63
本文介绍了为什么通过goto向后退时调用析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
会使用 goto 泄漏变量吗?

Possible Duplicate:
Will using goto leak variables?

在下面的示例中,当调用 goto 进行后退"时,将调用 A 的析构函数.为什么会这样呢?对象 a 不会离开范围,是吗?标准是否对 goto 的这种行为说了什么?

In the following example, when goto is called to go "backwards", the destructor of A is called. Why is it like that? Object a is not leaving its scope, is it? Does the standard say anything about this behavior regarding goto?

void f()
{
start:
    A a;
    goto start;
}

推荐答案

6.6跳转语句[stmt.jump]

第2段:

在退出合并范围时(无论如何完成),在该合并范围中构造的具有自动存储持续时间(3.7.3)的对象将按照与其构造相反的顺序进行销毁.[注意:有关临时信息,请参见12.2.— [end note]从循环中,从块中移出,或返回具有自动存储持续时间的初始化变量会涉及破坏对象,该对象具有自动存储持续时间,该对象在从但不能转移到该点.(有关转入块的信息,请参见6.7).[注意:但是,可以在不破坏具有自动存储持续时间的类对象的情况下终止程序(例如,通过调用std :: exit()或std :: abort()(例如18.5)).—尾注]

On exit from a scope (however accomplished), objects with automatic storage duration (3.7.3) that have been constructed in that scope are destroyed in the reverse order of their construction. [ Note: For temporaries, see 12.2. —end note] Transfer out of a loop, out of a block, or back past an initialized variable with automatic storage duration involves the destruction of objects with automatic storage duration that are in scope at the point transferred from but not at the point transferred to. (See 6.7 for transfers into blocks). [Note: However, the program can be terminated (by calling std::exit() or std::abort() (18.5), for example) without destroying class objects with automatic storage duration. — end note ]

我认为重要的是:

或返回具有自动存储持续时间的初始化变量会涉及破坏

这篇关于为什么通过goto向后退时调用析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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