Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><code>std::back_inserter</code> creates an inserting iterator that inserts elements into a container. Each time this iterator is dereferenced, it calls <code>push_back</code> on the container to append a new element to the container.</p> <p>For a <code>std::vector</code> container, a call to <code>push_back</code> where <code>v.size() == v.capacity()</code> will result in a <em>reallocation</em>: a new array is created to store the contents of the vector, its current contents are copied into the new array, and the old array is destroyed. Any iterators into the vector at this time are <em>invalidated</em>, meaning they can no longer be used.</p> <p>In your program, this includes the input range defined by <code>begin(vec)</code> and <code>end(vec)</code> from which the <code>copy</code> algorithm is copying. The algorithm continues to use these iterators, even though they are invalidated, thus your program exhibits undefined behavior.</p> <hr> <p>Even if your container had sufficient capacity, its behavior would still be undefined: the specification states that, upon insertion, "if no reallocation happens, all the iterators and references before the insertion point remain valid" (C++11 §23.3.6.5/1). </p> <p>The call to <code>push_back</code> is equivalent to insertion at the end, so the end iterator (<code>std::end(vec)</code>) that you passed into <code>std::copy</code> is invalidated after a single call to <code>push_back</code>. If the input range is nonempty, the program therefore exhibits undefined behavior.</p> <hr> <p>Note that the behavior of your program would be well-defined if you used a <code>std::deque&lt;int&gt;</code> or a <code>std::list&lt;int&gt;</code>, because neither of those containers invalidates iterators when elements are appended.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload