std :: list-迭代器在移动时是否无效? [英] std::list - are the iterators invalidated on move?

查看:69
本文介绍了std :: list-迭代器在移动时是否无效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: list 迭代器具有一些非常好的属性-当删除任何其他元素,添加新元素甚至交换2个列表时,它们仍然有效(迭代器无效规则)!

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 时,迭代器在新容器中仍然有效,但是我也可以通过访问实际上具有预期

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<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

是否保证是否在移动 std :: list 时迭代器仍然有效的标准?其他容器呢?

Is it guaranteed by the standard if the iterators remain valid when std::list is moved? What about other containers?

推荐答案

对于一般的容器,只需 swap 保证迭代器保持有效(并指向交换的容器)。

For containers in general, only swap guarantees that iterators remain valid (and point into the swapped containers).

对于 std :: list ,特殊成员函数 splice()保证迭代器保留其预期的含义。

For std::list, the special member function splice() guarantees that iterators retain their expected meaning.

通常,从右值构造一个容器不保证迭代器;唯一的一般要求是,新容器与原始容器具有相同的值。

In general, constructing a container from an rvalue doesn't make guarantees about iterators; 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.)

这篇关于std :: list-迭代器在移动时是否无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆