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?
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?
1 Answer
Reset to default 4See
https://en.cppreference/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.
std::vector<T, A>
it can surely become invalid, and I don't see a strong reason for the standard to explicitly makestd::allocator
a special case for this scenario either. So I would assume that it is unsafe. – Weijun Zhou Commented Mar 17 at 9:19After 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.
which should cover it as being blessed!`` en.cppreference/w/cpp/container/vector/vector – bradgonesurfing Commented Mar 17 at 9:22