c++ garbage values in vector of pointer

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

When I do:

for(i=0; i

s

6条回答
  •  北海茫月
    2020-12-22 00:17

    When you do vectorA.push_back you may cause that vector to reallocate itself to increase capacity, which means all its contents are moved, which means any pointers to its contents that you have saved are made invalid.

    Maybe you want to rethink the whole idea of storing pointers to elements of a vector.

    If you can't drop the whole idea of storing pointers, but you know the required size in advance, you could use reserve before the loop:

    vectorA.reserve(size);
    for(i=0; i

    In this version, the pointers are valid until you either grow vectorA further or destroy it.

提交回复
热议问题