gpt4 book ai didi

c++ - 我是否保证在 move vector 后指向 std::vector 元素的指针有效?

转载 作者:IT老高 更新时间:2023-10-28 21:42:30 57 4
gpt4 key购买 nike

考虑这个例子:

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

尽管在许多 STL 实现中这可能会起作用,但我是否保证在 move std::vector 并且支持 v2 的内部缓冲区时不会执行重新分配 和以前的v1 一样吗?我无法在 Internet 和标准本身上找到此信息。

最佳答案

这是LWG open issue 2321 [强调我的]

Moving containers should (usually) be required to preserve iterators

[...]

[by Stephan T. Lavavej]
23.2.1 [container.requirements.general]/10 says that unless otherwise specified, "no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. [Note: The end() iterator does not refer to any element, so it may be invalidated. — end note]". However, move constructors and move assignment operators aren't given similar invalidation guarantees. The guarantees need several exceptions, so I do not believe that blanket language like /11 "Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container." is applicable.

[2014-02-13 Issaquah]

General agreeement on intent, several wording nits and additional paragraphs to hit.

STL to provide updated wording. Move to Open.

Proposed resolution:

[...]

no move constructor [...] of a container (except for array) invalidates any references, pointers, or iterators referring to the elements of the source container. [Note: The end() iterator does not refer to any element, so it may be invalidated. — end note]

所以,这是一个悬而未决的问题,对其基本解决方案已达成普遍共识(指针不应因 move 而失效)。但是,它还没有正式被接受(还没有?)作为一个缺陷。据我所知,所有主要的实现都不会在 move 构造时使指针无效,这似乎是一个普遍(隐含)提供的保证。

关于c++ - 我是否保证在 move vector 后指向 std::vector 元素的指针有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25347599/

57 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com