vector pointer locations guaranteed?

前端 未结 7 1709
无人及你
无人及你 2021-01-05 01:05

Suppose I have a vector of ints,

std::vector numbers;

that is populated with a bunch of values, then I say do this (where an ent

7条回答
  •  情歌与酒
    2021-01-05 01:22

    As all the others have said, when you call .resize() on a vector your pointers become invalidated because the (old array) may be completely deallocated, and an entirely new one may be re-allocated and your data copied into it.

    One workaround for this is don't store pointers into an STL vector. Instead, store integer indices.

    So in your example,

    std::vector numbers;
    int *oneNumber = &numbers[43]; // no. pointers invalidated after .resize or possibly .push_back.
    int oneNumberIndex = 43 ;      // yes. indices remain valid through .resize/.push_back
    

提交回复
热议问题