取消引用 list::end()

Dereference list::end()

我在玩 std::list。与其他容器类似,std::list::end 指的是 std::list (ref) 的尾后元素。

所以,我们希望下面的代码打印 1, 2, 3, 4, 5(确实如此):

std::list<int> l { 1, 2, 3, 4, 5 };
for (auto it = l.begin(); it != l.end(); ++it)
{
    std::cout << *it << ", ";
}
std::cout << std::endl;

然而,第二个代码片段的第二行应该打印5,但它确实:

std::cout << *l.begin() << std::endl;
std::cout << *l.end() << std::endl;

输出:15

为什么?我正在使用 GCC 11 和 C++11(顺便说一句,C++20 也一样)。

如果您在调试模式下构建,使用 -D_GLIBCXX_DEBUG 命令行标志,您可以看到原因:

/usr/include/c++/8/debug/safe_iterator.h:270:
Error: attempt to dereference a past-the-end iterator.

Objects involved in the operation:
    iterator "this" @ 0x0x7fff50ac8670 {
      type = __gnu_debug::_Safe_iterator<std::__cxx1998::_List_iterator<int>, std::__debug::list<int, std::allocator<int> > > (mutable iterator);
      state = past-the-end;
      references sequence with type 'std::__debug::list<int, std::allocator<int> >' @ 0x0x7fff50ac85d0
    }
Aborted

与其他容器一样,取消引用 end() 迭代器是未定义的。它只是碰巧在 non-debug 模式下工作。