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

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.


Yes. It's easier to visualize when you consider the "blocks" in which you declare a variable, i.e. between which pair of braces. The loop is a block in itself, and when it reaches the closing bracket, before the next iteration, all destructors of automatic storage variables declared in the loop are called.

might loop unrolling by the compiler change something about that?

As a rule of thumb don't think about what the compiler will optimize, because it still needs to guarantee the behaviour of your program, no matter what it does to optimize it. In that case, loop unrolling won't change anything to that effect if it happens.


The destructor is called for every iteration. Thus in some cases it’s faster to declare a variable outside the loop instead of in the loop. Assuming the following case:

std::string temp;
for(int i = 0; i < 10; ++i){
    temp = arr[i];
    doSomething(temp);
}

The destructor is not called when using the loop is executed. It just overrides temp.

But if you use std::string temp = arr[i] the constructor and destructor is called for each iteration. I think this adds a bit runtime in case you have a loop that is executed very often.

Tags:

C++

Destructor