这段代码怎么能像我看到的那样?

Wil*_*mKF 3 c++ puzzle fencepost

我有一个C++应用程序,有一次断言失败,我无法重现.这是失败一次的代码:

unsigned int test(std::vector<CAction> actionQueue) {
  unsigned int theLastCount = actionQueue.size() - 1;

  std::vector<CAction>::const_reverse_iterator rItr = actionQueue.rbegin();
  std::vector<CAction>::const_reverse_iterator rEndItr = actionQueue.rend();

  for (; rItr != rEndItr; ++rItr, --theLastCount) {
    const CAction &fileAction = *rItr;

    if (fileAction.test()) {
      continue;
    }
    return theLastCount;
  }

  assert(theLastCount == 0); // How could this fail?

  return theLastCount;
}
Run Code Online (Sandbox Code Playgroud)

不知何故,循环完成后,LastCount不为零.

从我对逻辑的解读,这应该是不可能的,除非:

  1. 其他一些线程方面影响了actionQueue(我认为不可能).
  2. 发生了一些瞬态内存损坏.

我在这里错过了一些愚蠢的东西,我的代码中是否有错误显示?请注意,在我看到这个的情况下,由于向量具有两个元素,因此应该将LastCount初始化为1.

Pup*_*ppy 5

我相信如果test()为所有fileActions传递,则LastCount将为-1.考虑:

theLastCount从actionQueue.size()开始.你在actionQueue中为每个项目递减一次 - 也就是说,它现在是actionQueue.size() - 1 - actionQueue.size()= -1.想一想.theLastCount保留当前迭代器的索引.但是当当前迭代器是rend时,那就是在数组开始之前的一个迭代器 - -1.

编辑:哦,它没有签名.但是因为你只测试等于零,所以积分溢出在这里并不重要.