最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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?

Share Improve this question edited Mar 18 at 9:27 JeJo 33.5k7 gold badges55 silver badges95 bronze badges asked Mar 17 at 9:01 bradgonesurfingbradgonesurfing 32.3k20 gold badges124 silver badges233 bronze badges 2
  • If it is std::vector<T, A> it can surely become invalid, and I don't see a strong reason for the standard to explicitly make std::allocator a special case for this scenario either. So I would assume that it is unsafe. – Weijun Zhou Commented Mar 17 at 9:19
  • 2 I just found on cpp reference 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. which should cover it as being blessed!`` en.cppreference/w/cpp/container/vector/vector – bradgonesurfing Commented Mar 17 at 9:22
Add a comment  | 

1 Answer 1

Reset to default 4

See

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.

发布评论

评论列表(0)

  1. 暂无评论