c++ garbage values in vector of pointer

前端 未结 6 1952
青春惊慌失措
青春惊慌失措 2020-12-22 00:12

When I do:

for(i=0; i

s

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-22 00:24

    Read the documentation of std::vector::push_back

    First the description:

    Adds a new element at the end of the vector, after its current last element. The content of val is copied (or moved) to the new element.

    This effectively increases the container size by one, which causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.

    Then about validity of iterators:

    If a reallocation happens, all iterators, pointers and references related to the container are invalidated.

    So, when you add an object to the vector, all the pointers pointing to objects in that vector may become invalid - unless you've guaranteed that the vector has enough capacity with std::vector::reserve.

    Invalid means that the pointer no longer points to a valid object and dereferencing it will have undefined behaviour.

    In the latter code, you never add objects to the pointed-to vector after you've stored the pointers, so the pointers are valid.

提交回复
热议问题