Edit: slow ...
Yes, a new object 'newClass' is created and destructed on every iteration of the lines 19-24 loop. Yes, memory is allocated for it from the stack and later deallocated. Is it more or less likely that the stack pointer is at same address at the start of each iteration?
Does that even have any significance, at which point in stack an automatic variable of each iteration exists? No.
The range-syntax for loop simply repeats the same phenomenon. These are equivalent:
1 2 3 4 5 6 7 8 9 10
|
// A
for ( auto x : myVector ) {
std::cout << x;
}
// B
for ( size_t i = 0; i < myVector.size(); ++i ) {
auto x = myVector[i];
std::cout << x;
}
|
The 'x' is an automatic variable that lives only one iteration, just like the newClass in the previous loop. Each iteration has different instance, but "miraculously" the compiler has
allocated same bits of stack each time.
1) How can there be multiple different values in the same memory location? |
A) Like this:
1 2 3 4
|
int foo;
foo = 7;
foo = 42;
foo = 0;
|
Value is different at different moment in time, not simultaneously.
B) Like this:
1 2 3 4
|
std::vector bar = { 7, 42, 0 };
assert( &bar[0] != &bar[1] &&
&bar[0] != &bar[2] &&
&bar[1] != &bar[2] );
|
The different values exists simultaneously in the vector, where they are in different addresses (in free store, not in stack).
2) Don't the automatic variables "newClass" cease to exist after the "for" loop? |
Not just after the loop. At end of each iteration:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <iostream>
struct Foo
{
int myInt;
Foo( int x ) : myInt( x ) { std::cout << "Foo() "; }
~Foo() { std::cout << " ~Foo()\n"; }
};
int main()
{
for( int i = 0; i < 10; ++i ) {
Foo foo( i );
std::cout << foo.myInt;
}
return 0;
}
|