title: Keeping std::list iterators valid through insertion
body: <p><em>Note:</em> This is not a question whether I should "use list or deque". It's a question about the validity of iterators in the face of <code>insert()</code>.</p>
  
  <hr>
  
  <p>This may be a simple question and I'm just too dense to see the right way to do this. I'm implementing (for better or worse) a network traffic buffer as a <code>std::list&lt;char&gt; buf</code>, and I'm maintaining my current read position as an iterator <code>readpos</code>.</p>
  
  <p>When I add data, I do something like</p>
  
  <pre><code>buf.insert(buf.end(), newdata.begin(), newdata.end());
  </code></pre>
  
  <p>My question is now, how do I keep the <code>readpos</code> iterator valid? If it points to the middle of the old <code>buf</code>, then it should be fine (by the iterator guarantees for std::list), but typically I may have read and processed all data and I have <code>readpos == buf.end()</code>. After the insertion, I want <code>readpos</code> <em>always</em> to point to the next unread character, which in case of the insertion should be the first inserted one.</p>
  
  <p>Any suggestions? (Short of changing the buffer to a <code>std::deque&lt;char&gt;</code>, which appears to be much better suited to the task, as suggested below.)</p>
  
  <p><strong>Update:</strong> From a quick test with GCC4.4 I observe that deque and list behave differently with respect to <code>readpos = buf.end()</code>: After inserting at the end, readpos is broken in a list, but points to the next element in a deque. <em>Is this a standard guarantee?</em></p>
  
  <p>(According to <a href="http://www.cplusplus.com/reference/stl/deque/insert/" rel="nofollow">cplusplus</a>, any deque::insert() <em>invalidated</em> all iterators. That's no good. Maybe using a counter is better than an iterator to track a position in a deque?)</p>