Vector of vectors scoping query - When you copy a local Vector to a none local vector, does push_back copy?

1 week ago 4
ARTICLE AD BOX

I can't seem to find any answers to this, hoping some of you smart people can help.

If I run the following simple code , I get a vector of vectors that I can clearly see in the Watch window:

int main() { std::vector<std::vector<int>> v2 = { {0,0,0}, {1,1,1} }; return 0; }

If I run the following code I was expecting to get the same result:

int main() { std::vector<std::vector<int>> v2; for(int i = 0; i< 2; i++) { std::vector<int> v1(3,i); v2.push_back(v1); } }

Let me explain why I thought I would get the same result.

The vector v1 is scoped to the for loop, this is created as expected on each iteration. When it is pushed back to v2, I was expecting a copy to be generated and placed into v2, which does happen on the first iteration. v1 then goes out of scope at the end of the for loop, but the copy remains within v2.

This all seems to happen correctly on the first iteration - I can see v1, and the copy within v2.

On the second iteration though, v1 is created as expected and I can see it in the Watch window. However, when it is added to v2 it seems to overwrite the original v1 copy with an invalid memory address.

I'm sure I'm being really daft here but I can't quite see what the problem is. Any advice on how to achieve what I am trying to achieve?

Read Entire Article