The address of my object in a vector changes

This question already has an answer here:

  • Iterator invalidation rules 4 answers

  • You are calling vec.push_back(a) within your for loop. Therefore the vector may re-allocate the underlying array if it runs out of space. Therefore the address of the previous elements are no longer valid if they were copied to the new memory location.

    For example say you allocated 3 elements and stored their addresses. After pushing back a 4th element the vector has to reallocate. That means the first 3 elements will be copied to a new location, then the 4th will be added after that. Therefore the address you had stored for the first 3 are now invalid.


    Iterators (and references and object adresses) are not guaranteed to be preserved when you call vector<T>::push_back() . If the new size() is greater than current capacity() , a reallocation will happen and all the elements are moved or copied to the new location.

    To avoid this, you can call reserve() before you start inserting.


    One of the main features of std::vector is that it stores its elements in contiguous memory (which is great for performance when you visit vector's items on modern CPUs).

    The downside of that is when the pre-allocated memory for the vector is full and you want to add a new item (eg calling vector::push_back() ), the vector has to allocate another chunk of contiguous memory, and copy/move the data from the previous location to the new one. As a consequence of this re-allocation and copy/move, the address of the old items can change.

    If for some reason you want to preserve the address of your objects, instead of storing instances of those objects inside std::vector , you may consider having a vector of pointers to objects. In this case, even after the reallocation, the object pointers won't change.

    For example, you may use shared_ptr for both the vector 's items and the multimap 's key:

    vector<shared_ptr<const A>> vec;
    
    multimap<shared_ptr<const A>, const double> mymultimap;
    
    链接地址: http://www.djcxy.com/p/73334.html

    上一篇: 添加元素时,c ++中的矢量迭代器是否会损坏?

    下一篇: 我的对象在矢量中的地址发生了变化