Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the destructor of a local object inside a loop guaranteed to be called before the next iteration?

Tags:

c++

destructor

When I have a loop and inside this loop create a new stack variable (not allocating it on the heap and variable holding it declared inside the loop body), is the destructor of this object guaranteed to be called before the next iteration starts, or might loop unrolling by the compiler change something about that?

like image 948
matthias_buehlmann Avatar asked Dec 06 '19 12:12

matthias_buehlmann


People also ask

Does the destructor automatically get called?

A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete .

Do destructors need to be called?

No. You never need to explicitly call a destructor (except with placement new ). A class's destructor (whether or not you explicitly define one) automagically invokes the destructors for member objects. They are destroyed in the reverse order they appear within the declaration for the class.

Is destructor called after return?

While returning from a function, destructor is the last method to be executed. The destructor for the object “ob” is called after the value of i is copied to the return value of the function. So, before destructor could change the value of i to 10, the current value of i gets copied & hence the output is i = 3.

What happens when destructor is not called?

It is automatically called when an object is destroyed, either because its scope of existence has finished (for example, if it was defined as a local object within a function and the function ends) or because it is an object dynamically assigned and it is released using the operator delete.


1 Answers

From n4800:

§6.3.3 Block Scope:

A name declared in a block (8.3) is local to that block; it has block scope. Its potential scope begins at its point of declaration (6.3.2) and ends at the end of its block. A variable declared at block scope is a local variable.

§10.3.6 Destructors:

A destructor is invoked implicitly [...] when the block in which an object is created exits (8.7)

§4.1.1 Abstract machine:

This provision is sometimes called the “as-if” rule, because an implementation is free to disregard any requirement of this document as long as the result is as if the requirement had been obeyed, as far as can be determined from the observable behavior of the program.

[Emphasis mine]

So, yes. Your variable goes out of scope at the end of the loop (which is a block) and hence its destructor is called as far as anyone observing the behavior of the program can tell.

like image 147
Paul Evans Avatar answered Nov 15 '22 22:11

Paul Evans