是否保证C ++析构函数直到块结束才被调用? [英] Is a C++ destructor guaranteed not to be called until the end of the block?

查看:78
本文介绍了是否保证C ++析构函数直到块结束才被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的C ++代码中,我是否保证在执行//更多代码之后,在之后会调用〜obj()析构函数?还是如果编译器检测到未使用obj对象,便可以允许它更早地对其进行销毁?

In the C++ code below, am I guaranteed that the ~obj() destructor will be called after the // More code executes? Or is the compiler allowed to destruct the obj object earlier if it detects that it's not used?

{
  SomeObject obj;
  ... // More code
}

我想使用这种技术来省去记住在块的末尾重置标志的麻烦,但是我需要为整个块保持该标志的设置.

I'd like to use this technique to save me having to remember to reset a flag at the end of the block, but I need the flag to remain set for the whole block.

推荐答案

您可以接受-这是C ++编程中非常常用的模式.在C ++ Standard第12.4/10节中,指的是何时调用析构函数:

You are OK with this - it's a very commonly used pattern in C++ programming. From the C++ Standard section 12.4/10, referring to when a destructor is called:

对于具有自动储存期限当对象所在的块时创建的出口

for a constructed object with automatic storage duration when the block in which the object is created exits

这篇关于是否保证C ++析构函数直到块结束才被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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