c++c++20stdvectorstdmovestd-span

Does std::span<T> remain valid and point to the new std::vector<T> upon move of a std::vector<T>


If we have an initialized std::vector

std::vector<T> v = ...;

then construct a span into that vector

std::span<T> s = std::span<T>(v.begin(), 10);

and then move the original vector

std::vector<T> x = std::move(v);

Is span s still valid? That it works in most implementations I have no doubt. Move is implemented as simple pointer swap and no reallocation occurs. It is then expected that the span still points to the original memory which is now managed by x. But this doesn't mean it is sanctioned to always work. Is this undefined behaviour that could be at risk of failure?


Solution

  • See

    https://en.cppreference.com/w/cpp/container/vector/vector

    After container move construction (overload (8)), references, pointers, and iterators (other than the end iterator) to other remain valid, but refer to elements that are now in *this. The current standard makes this guarantee via the blanket statement in [container.reqmts]/67, and a more direct guarantee is under consideration via LWG issue 2321.