If I use the following in a loop:
ostringstream glob;
glob << "some words";
cout<< "this is bob"<<glob.str()<<endl;
glob is reset each iteration. However if I declare glob outside of the loop then “some words” keep getting added each iteration resulting in a longer and longer string.
I am trying to understand why. Is this because this variable is being popped off the stack each time the loop goes round?
I thought that if I were “redclaring” glob each loop then I would get an error, but I dont….
To clarify, you are asking about the difference between this:
and this:
In the first, ‘glob’ is initialised once, before the loop, as its scope is outside the loop body. In the second ‘glob’ is within the loop body (within the braces that define the loop scope) and hence is newly placed on the stack and initialised with each iteration (and destroyed at the end of each iteration).