【问题标题】:Deque random access iterator comparison produces unexpected resultsDeque 随机访问迭代器比较产生意外结果
【发布时间】:2015-05-13 16:30:34
【问题描述】:

我有这个小 sn-p,它在 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. 为什么?

【问题讨论】:

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


    【解决方案1】:

    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)
    

    【讨论】:

    • 好的。计算钳位 i 迭代器的正确方法是什么?
    • 正确,显然 ;-) itr - std::min(k, std::distance(values.begin(), itr))
    • 基本上,不要减少超过从begin()itr 的距离。这并不复杂,您只需要小心。
    • 谢谢!顺便说一句,不是我的代码,只是在调试时遇到了这个问题。
    【解决方案2】:

    谁是对的,GCC 还是 Visual Studio?

    两者。

    为什么?

    递减begin() 是未定义的行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-29
      • 2022-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-06
      相关资源
      最近更新 更多