C++: vector of pointer loses the reference after push_back()

前端 未结 4 1817
梦谈多话
梦谈多话 2021-01-04 09:04

In my code a have a global vector of Node object and a local vector of Node pointers:

#include
#include
#include

         


        
4条回答
  •  悲哀的现实
    2021-01-04 09:09

    What you are doing is undefined behavior for your vector p because the vector v can change where it's objects are stored.

    A std::vector's memory is contiguous, so it may, after a number of push_backs, have to allocate a new block memory and copy it's contents to the new block. This will invalidate all the pointers that happened to point to the old memory location.

提交回复
热议问题