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?
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 .
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With