Is a C++ destructor guaranteed not to be called un

2019-02-11 10:35发布

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++ raii
8条回答
\"骚年 ilove
2楼-- · 2019-02-11 11:20

Yes, the C++ standard has very specific requirements about when objects are destroyed (in §12.4/10), and in this case it must not be destroyed until after all the other code in the block has finished executing.

查看更多
贪生不怕死
3楼-- · 2019-02-11 11:20

All of the answers here address what happens with named objects, but for completeness, you probably should know the rule for temporary/anonymous objects too. (e.g. f(SomeObjectConstructor() or f(someFunctionThatReturnsAnObject()))

Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception. (12.2/3 from the ISO C++98 standard)

which basically means that temporarily generated objects persist until the next statement. Two exceptions are for temporaries generated as part of an object's initialization list (in which case the temporary is destroyed only after the object is fully constructed) and if a reference is made to a temporary (e.g. const Foo& ref = someFunctionThatReturnsAnobject()) (which case the lifetime of the object is the lifetime of the reference).

查看更多
登录 后发表回答