This material is explained in every college-level course on operating system design and / or compiler development.
The objects in question are created on the stack, and at the end of the scope they exit the scope on the stack. The stack grows and shrinks accordingly, and since the same exact objects are created (and destroyed) at each iteration of the loop, the stack grows and shrinks by the same amount, so the same objects always get an instance in the same place on the stack .
In practice, the compiler can do some optimizations and calculate the large stack size that each function will use most of the time, and thus drag the stack over the large amount that the function will need; but it goes too far into the weeds ...
This is the shortest answer that I can give without going into a whole lecture on what a stack is, etc.
Now another object is allocated on the heap. Focus on the fact that at the end of the loop, the object you nested in the vector still exists, and the object βaβ is destroyed, and you will begin to see the difference. At each iteration of the loop, an βaβ object is created and then destroyed at the end of the loop (and created again at the beginning of the loop), while the object that you insert into the vector still exists.
Sam varshavchik
source share