admin管理员组文章数量:1387420
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.
本文标签:
版权声明:本文标题:c++ - Does std::span<T> remain valid and point to the new std::vector<T> upon move of a std::vector& 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744571086a2613344.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
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