Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Just to clarify the "extra copy" @ecatmur describes, if <code>push_back</code> received its argument by value, what would happen would be that you'd start with your object. A copy of that would be passed to <code>push_back</code> as its parameter. Then <code>push_back</code> would create a copy of <em>that</em> to put into the vector itself.</p> <p>Since the real implementation of <code>push_back</code> receives its argument by reference, it (<code>push_back</code>) creates the new object in the vector directly as a copy of your original object.</p> <p>As already mentioned, yes, with C++11 using move semantics, it would be possible (though probably not particularly advantageous) to pass the argument by value, and then move the value from that argument into the new object in the vector. If what you were putting in the vector was, say, a string that mostly just contains a pointer and a couple of "book keeping" fields (amount of memory allocated, amount of memory currently in use), that would be <em>almost</em> as efficient as passing a reference, because a move can just do a shallow copy -- copy the pointer and book keeping values themselves, instead of all the data it points at. If, however, the object in question held all its data directly (i.e., not a pointer), then a move would be just as slow as a copy.</p> <p>Passing by reference, avoids <em>all</em> that copying, so even for something like a string, it's generally faster still (for a case like this that the original object can't be invalidated). It also has the minor advantage of working with C++98/03, not just C++11.</p>
 

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