title: Got singular iterator error in looping with iterator and pop_back
body: <p>Giving the below code (say it's named <code>deque.cpp</code>)</p>
  
  <pre><code>#include &lt;cstdio&gt;
  #include &lt;deque&gt;
  
  int main()
  {
    std::deque&lt;int&gt; d = {1, 2, 3};
    for (auto it = d.rbegin(); it != d.rend();) {
      printf("it: %d\n", *it);
      ++it;
      d.pop_back();
    }
    return 0;
  }
  </code></pre>
  
  <p>Compile with <code>g++ -std=c++11 -o deque deque.cpp</code>, it runs well:</p>
  
  <pre><code>$ ./deque
  it: 3
  it: 2
  it: 1
  </code></pre>
  
  <p>But if compile with <code>-D_GLIBCXX_DEBUG</code> (<code>g++ -std=c++11 -o deque_debug deque.cpp -D_GLIBCXX_DEBUG</code>, it gets below error:</p>
  
  <pre><code>$ ./deque_debug
  it: 3
  /usr/include/c++/4.8/debug/safe_iterator.h:171:error: attempt to copy-
      construct an iterator from a singular iterator.
  ...
  </code></pre>
  
  <p>It looks like the second loop's <code>++it</code> is constructing from an singular iterator.
  But I think after the first loop's <code>++it</code>, the iterator points to 2, and <code>pop_back()</code> should not invalidate it. Then why the error occurs?</p>
  
  <p>Note: I know the code could be re-write as below:</p>
  
  <pre><code>  while (!d.empty()) {
      auto it = d.rbegin();
      printf("it: %d\n", *it);
      d.pop_back();
    }
  </code></pre>
  
  <p>And the error will be gone.</p>
  
  <p>But I do want to know what exactly happens on the error code. (Does it mean the reverse iterator dose not actually point to the node I expect, but the one after it?)</p>
  
  <hr>
  
  <p><strong>Update:</strong> @Barry's answer resolved the question.
  Please let me put an extra related question: the code </p>
  
  <pre><code>  for (auto it = d.rbegin(); it != d.rend();) {
      printf("it: %d\n", *it);
      d.pop_back();
      ++it;   // &lt;== moved below pop_back()
    }
  </code></pre>
  
  <p>is expected to be wrong, where <code>++it</code> should be operating on an invalidated iterator. But why the code does not cause error?</p>