iterator become invalid after swapping with temporary container
It's said that if swap two container's value, the iterator will not become invalid.
so following code works fine
vector<int> v1;
v1.push_back(1);
vector<int>::iterator i = v1.begin();
vector<int> v2(v1);
v2.swap(v1);
cout<<*i<<endl; //output 1
but when I turned to a temporary container, the iterator become invalid, and the program crashed.
vector<int> v1;
v1.push_back(1);
vector<int>::iterator i = v1.begin();
vector<int>(v1).swap(v1);
cout<<*i<<endl; //i become invalid and program crashes here
This might be a stup开发者_StackOverflowid question, but I cann't figure out what's wrong.
I believe it's because the iterator belongs to the container that you swap it with. When you swap it with a temporary, the iterator points to a member of the temporary, then the temp is destroyed and the iterator becomes invalid.
I don't know for sure that's how it works, but it's the only way I could think of that iterators for a vector could stay valid after a swap (just swapping the internal pointers to the arrays, not allocating new arrays and copying, etc).
The iterator here is little more than simply a pointer to an item in the array.
In both cases you swap the internal array in the vectors. In the first case the iterator now points into the array owned by the second vector. In the second case the iterator points into the array owned and already released by the temporary vector.
Because scope of following temporary remains only till the end of statement (;
)
vector<int>(v1).swap(v1);
Now v1
contains a copy of itself, which gets destroyed at the semicolon. Thus iterator i
points to an invalid iterator after that ;
.
Your 2nd code excerpt is creating copy of v1 and then swapping with v1. This destroys the v1 vector, and that invalidate the iterator.
精彩评论