What happen to pointers when vectors need more memory and realocate memory?

后端 未结 3 1541
花落未央
花落未央 2020-12-11 03:17

When vector needs more memory it will reallocate memory somewhere, I don\'t know where yet! and then pointers become invalid, is there any good explanation on this?

3条回答
  •  [愿得一人]
    2020-12-11 03:26

    When you use std::vector, the class takes care of all the details regarding memory allocation, pointers, resizing and so on.

    The vector class exposes its contents through iterators and references. Mutations of the vector will potentially invalidate iterators and references because reallocation may be necessary.

    It is valid to access the contents using pointers because the vector class guarantees to store its elements at contiguous memory locations. Clearly any mutation of the list will potentially invalidate any pointers to its contents, because of potential reallocation. Therefore, if you ever access an element using pointers, you must regard those pointers as invalid once you mutate the vector. In short the same rules apply to pointers to the contents as do to references.

    If you want to maintain a reference to an item in the vector, and have this reference be valid even after mutation, then you should remember the index rather than a pointer or reference to the item. In that case it is perfectly safe to add to the end of the vector and your index value still refers to the same element.

提交回复
热议问题