Am I guaranteed that pointers to std::vector elements are valid after the vector is moved?

前端 未结 2 1928
萌比男神i
萌比男神i 2020-12-16 10:52

Considering this example:

std::vector v1 = { 1, 2, 3 };
const int* i = &v1[1];
std::vector v2(std::move(v1));
std::cout << *i         


        
2条回答
  •  独厮守ぢ
    2020-12-16 11:25

    cppreference.com states that:

    ... have the option, but aren't required, to move any resources held by the argument...

    It looks like std::move just is a hint to the library that an optimization by transferring ownership is possible, but it's up to the library whether to do that optimization or not.

    That means that you should assume that all pointers to elements are invalidated after the move.

提交回复
热议问题