How could this code behave as I saw?

I have a C ++ application that had a one-time failure that I cannot reproduce. Here is the incorrect code:

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;
}

Somehow, after the loop ended, theLastCount was not equal to zero.

From my reading of logic, this should be impossible if:

  • Some other side of the thread produced an actionQueue (which I think is impossible).
  • Some damage occurred with short-term memory.

I'm missing something stupid here, is there an error in my code? Please note that in the case when I saw this, theLastCount had to be initialized with one, since the vector had two elements.

+3
source share
5 answers

, test() fileActions, theLastCount -1. :

theLastCount actionQueue.size() -1. actionQueue, actionQueue.size() - 1 - actionQueue.size() = -1. . theLastCount . , , -1.

: , . , .

+5

actionQueue ,

unsigned int theLastCount = actionQueue.size() - 1;

theLastCount . , (rbegin() == rend() ), theLastCount .

+2
void test(std::vector<CAction> actionQueue) 
{
  unsigned int theLastCount = actionQueue.size() - 1;
  /** Omitted code ***/
  {
    /** Omitted code ***/
    return theLastCount;
  }
  return theLastCount;
}

, . . void, unsigned int!! ?


, :

assert(theLastCount == -1);//correct assert!

, test() , LastCount -1. , theLastCount , . -1.

. theLastCount unsigned int int.

+1

Comment and run your code before posting it here! Firstly, this code does not compile (I am not telling you why - you can ask your compiler). Secondly, your statement can never be executed, because theLastCount will always be (unsigned int) -1.

+1
source

What if the queue is empty?

theLastCount will be -1, and then ... :-)

0
source

Source: https://habr.com/ru/post/1785651/


All Articles