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

后端 未结 3 1534
花落未央
花落未央 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:44

    When you add or remove items from a vector, all iterators (and pointers) to items within it are invalidated. If you need to store a pointer to an item in a vector, then make the vector const, or use a different container.

    It shouldn't matter to you where the vector stores things. You don't need to do anything, just let it do its job.

提交回复
热议问题