gpt4 book ai didi

c++ - std::list 从标准角度看哨兵节点

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:27:34 24 4
gpt4 key购买 nike

代码示例:


list<int> mylist{10, 20, 30, 40};
auto p = mylist.end();
while (true)
{
p++;
if (p == mylist.end()) // skip sentinel
continue;
cout << *p << endl;
}

我想知道,从标准(C++17、n4810)的角度来看,这段代码在多大程度上是合法的?我正在寻找与上述示例相关的双向迭代器要求,但没有成功。

我的问题是:

能够通过end(),是实现细节还是标准要求?

最佳答案

引用在线提供的最新草案。 [iterator.requirements.general]/7

Just as a regular pointer to an array guarantees that there is a pointer value pointing past the last element of the array, so for any iterator type there is an iterator value that points past the last element of a corresponding sequence. These values are called past-the-end values. Values of an iterator i for which the expression *i is defined are called dereferenceable. The library never assumes that past-the-end values are dereferenceable.

我相信这不仅适用于 end(),也适用于之后发生的事情。请注意,该标准并未明确规定永远不应取消引用 end()

Cpp17Iterator requirements table声明对于表达式 *rr 应该是可解引用的:

enter image description here

尾后迭代器被认为是不可递增的迭代器,递增它(就像您在 while 循环开始时所做的那样)会导致未定义的行为。

使用 std::advance 时也可能发生类似您尝试做的事情.

本书"The C++ Standard Library: A Tutorial and Reference" Nicolai Josuttis 引用了这句话:

Note that advance() does not check whether it crosses the end() of a sequence (it can't check because iterators in general do not know the containers on which they operate). Thus, calling this function might result in undefined behavior because calling operator ++ for the end of a sequence is not defined.

关于c++ - std::list 从标准角度看哨兵节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56162232/

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