您的位置:首页 > 其它

vecor预分配内存溢出2

2016-07-25 10:35 225 查看
vector预分配内存溢出导致原始的 迭代器 失效

consider what happens when you add the one additional object that causes the vector to reallocate storage and move it elsewhere. The iterator’s pointer is now pointing off into nowhere:

This illustrates the concept of iterator invalidation. Certain operations cause internal changes to a container’s underlying data, so any iterators in effect before such changes may no longer be valid afterward.

#include<iostream>
#include<iterator>
#include<vector>
using namespace std;
int main()
{
vector<int> vi(10, 0);
ostream_iterator<int> out(cout, " ");
vector<int>::iterator i = vi.begin();
*i = 47;
copy(vi.begin(), vi.end(), out);
cout << endl;
//force it to move memory(could also just add enough objects)
vi.resize(vi.capacity() + 1);
//now i points to wrong memory
*i = 48;
copy(vi.begin(), vi.end(), out);//no change to vi[0]
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: