Just to clarify the โextra copy," @ecatmur describes if push_back got its argument by value, what happens is that you will start from your object. A copy of this will be passed to push_back as a parameter. Then push_back will create a copy of this to fit into the vector itself.
Since the actual push_back implementation takes its argument by reference, it ( push_back ) creates a new object in the vector directly as a copy of the original object.
As already mentioned, yes, with C ++ 11, using move semantics, it would be possible (although probably not particularly beneficial) to pass an argument by value, and then transfer the value from this argument to a new object in the vector. If what you put in the vector was, say, a string that basically contains a pointer and a couple of โbook storageโ fields (the amount of allocated memory, the amount of memory used), which will be almost as efficient as passing a link, because moving can just make a shallow copy - copy the pointer and values โโto store books, and not all the data it points to. If, however, the object in question contains all its data directly (i.e., not a pointer), then the move will be as slow as the copy.
Following the link avoids all this copying, so even for something like a string, it is usually even faster (for such a case that the original object cannot be canceled). It also has a slight advantage in working with C ++ 98/03, and not just with C ++ 11.
Jerry Coffin
source share