问题描述
在下面的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:
这篇关于是否保证C ++析构函数直到块结束才被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!