std::list 上的 splice() 和迭代器失效

2022-01-10 00:00:00 list containers iterator c++

list::splice() 的 3 参数形式将单个元素从一个列表移动到另一个列表.SGI 的文档 明确指出所有迭代器,包括一个指向正在移动的元素仍然有效.Roguewave 的文档 没有说明 splice() 方法,而 C++ 标准明确声明它使所有迭代器和对被拼接元素的引用无效.

The 3-argument form of list::splice() moves a single element from one list to the other. SGI's documentation explicitly states that all iterators, including the one pointing to the element being moved remain valid. Roguewave's documentation does not say anything about iterator invalidation properties of splice() methods, whereas the C++ standard explicitly states that it invalidates all iterators and references to the element being spliced.

splicing() 在实践中按照 SGI 的定义工作,但在微软 STL 实现的调试/安全 SCL 版本(严格遵循标准的字母)中出现断言失败(取消引用无效迭代器).

splicing() in practice works as defined by SGI, but I get assertion failure (dereferencing invalid iterator) in debug / secure SCL versions of microsoft's STL implementation (which strictly follows the letter of the standard).

现在,我使用 list 正是因为我想在列表之间移动一个元素,同时保持指向它的迭代器的有效性.该标准对原始 SGI 规范做出了极其无益的更改.

Now, I'm using list exactly because I want to move an element between lists, while preserving the validity of the iterator pointing to it. The standard has made an extremely unhelpful change to the original SGI's specification.

我该如何解决这个问题?或者我应该务实一点,把头埋在沙子里(因为拼接确实不会在实践中使迭代器失效――即使在 MS 的实现中,一旦迭代器调试被关闭).

How can I work around this problem? Or should I just be pragmatic and stick my head in the sand (because the splicing does not invalidate iterators in practice -- not even in the MS's implementation, once iterator debugging is turned off).

推荐答案

好吧,这似乎是标准的缺陷,根据 this 和 这个链接.似乎把头埋在沙子里"是个好策略,因为它会在新的库版本中得到修复.

Ok, this seems to be a defect in the standard, according to this and this link. It seems that "sticking the head in the sand" is a good strategy, since it will be fixed in new library versions.

相关文章