c++ - 双端队列随机访问迭代器比较产生意外结果

标签 c++ visual-c++ gcc iterator deque

我有这个小片段,它在 GCC 上表现得非常好(正如预期的那样)。

#include <deque>
#include <iostream>
#include <algorithm>

std::deque<int> values = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int main()
{
    typedef std::deque<int>::iterator buf_iterator;

    buf_iterator itr = values.begin() + 1;

    const int K = 5;

    buf_iterator i = std::max(itr - K, values.begin());

    int pos = i - values.begin();

    std::cout << *i << std::endl;

    return 0;
}

但是,在 MSVC 2013 和 2015 上运行会产生调试断言:“deque iterator is not dereferencable”。在这种情况下,pos 的值为 -4,而应为零。

  1. 谁是对的,GCC 还是 Visual Studio?
  2. 为什么?

最佳答案

itr - K 是未定义的行为,因为它在开始之前递减指针,即它等同于:

auto it = values.begin();
--it;

这是未定义的。

GCC 将通过定义的 _GLIBCXX_DEBUG 捕捉到这个:

/home/jwakely/gcc/5/include/c++/5.0.0/debug/safe_iterator.h:428:error: 
    attempt to retreat a dereferenceable iterator 5 steps, which falls 
    outside its valid range.

Objects involved in the operation:
iterator @ 0x0x7fff6fdb3450 {
type = N11__gnu_debug14_Safe_iteratorINSt9__cxx199815_Deque_iteratorIiRiPiEENSt7__debug5dequeIiSaIiEEEEE (mutable iterator);
  state = dereferenceable;
  references sequence with type `NSt7__debug5dequeIiSaIiEEE' @ 0x0x606360
}
Aborted (core dumped)

关于c++ - 双端队列随机访问迭代器比较产生意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28994162/

相关文章:

c++ - 指针和非指针类型的重载 -> 运算符

c++ - 将非常大且旧的 C++Builder 代码移植/重新编码到 Qt 或 CLI/Mono

适用于 68HC12/68HC12X 的 GCC 工具链

c++ - 无法编译 C++ file.cpp。 C++98模式

c# - 模块窗口中缺少一些 DLL

c++ - 在没有全局或静态变量的情况下配置 Bison 和 Flex

c++ - 如何通过linux套接字发送图像数据

visual-c++ - 列出可用的平台工具集

c++ - 对 vector C++ 中的上界

c++ - 从子类 : gcc vs msvc 访问 protected 成员