Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

raii - Is a C++ destructor guaranteed not to be called until the end of the block?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...