【问题标题】:Dereference list::end()取消引用列表::end()
【发布时间】:2021-01-10 23:00:07
【问题描述】:

我在玩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;

但是,第二个代码 sn-p 的第二行应该打印5,但它确实:

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

输出:15

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

【问题讨论】:

  • 未定义的行为是未定义的,包括“产生垃圾数据”或“奇迹般地产生你想要的数据”或“恶魔飞出你的鼻子”。对此没有“答案”。
  • 如果它应该打印5,你认为它应该打印什么?
  • @Barmar 是的,我明白了,它是未定义的。虽然在链接上找不到。老实说,我预计会崩溃,或者最大 int,或者 smth :)

标签: c++11 gcc stdlist


【解决方案1】:

如果您在调试模式下构建,您可以使用-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() 迭代器是未定义的。它只是在非调试模式下偶然工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多