简体   繁体   English

std :: list - 移动时失效的迭代器是什么?

[英]std::list - are the iterators invalidated on move?

std::list iterators have some very nice properties - they remain valid when any other element is removed, when a new element is added and even when 2 lists are swapped ( Iterator invalidation rules )! std::list迭代器有一些非常好的属性 - 当删除任何其他元素,添加新元素时,甚至当交换2个列表时,它们仍然有效( 迭代器失效规则 )!

Considering following code behaviour and that the iterators are implement by a form of pointer to the actual node which doesn't change when the list is moved, my guess is that the iterators are still valid in the new container when a std::list is moved, but also I can be in the UB area here by accessing invalid memory which actually has the "expected" value. 考虑以下代码行为并且迭代器是通过指向实际节点的指针形式实现的,当移动列表时它不会改变,我的猜测是当std::list是新的容器时,迭代器仍然有效。移动,但我也可以通过访问实际具有“预期”值的无效内存进入UB区域。

std::list<int> l1{3, 2, 1};
std::list<int> l2;

auto it = std::prev(l1.end());
std::cout<<l1.size()<<" "<<l2.size()<<" "<<*it<<std::endl;

l2 = std::move(l1);
std::cout<<l2.size()<<" "<<*it<<std::endl;

3 0 1
3 1

Is it guaranteed by the standard if the iterators remain valid when std::list is moved? 如果移动std::list时迭代器仍然有效,那么它是否由标准保证? What about other containers? 其他容器怎么样?

For containers in general, only swap guarantees that iterators remain valid (and point into the swapped containers). 对于通常的容器,只有swap保证迭代器保持有效(并指向交换的容器)。

For std::list , the special member function splice() guarantees that iterators retain their expected meaning. 对于std::list ,特殊成员函数splice()保证迭代器保持其预期含义。

In general, constructing a container from an rvalue doesn't make guarantees about iterators; 通常,从rvalue构造容器不能保证迭代器; the only general requirement is that the new container has the "same value" as the container it was constructed from had originally. 唯一的一般要求是新容器与最初构造的容器具有“相同的值”。

(You can imagine debug iterator implementations that store a reference to the container, and that reference would become dangling after a move.) (您可以想象调试迭代器实现,它存储对容器的引用,并且该引用在移动后将变为悬空。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM