问题描述
我在玩std::list
。与其他容器类似,std::list::end
指std :: list(ref)的past-the-end元素。
因此,我们希望下面的代码可以打印1,2,3,4,5
(它会这样做):
std::list<int> l { 1,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;
输出:1
和5
。
为什么?我正在使用GCC 11和C ++ 11(与C ++ 20 btw相同)。
解决方法
您可以使用-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()
迭代器的引用。它只是偶然地在非调试模式下工作。