C ++ STL Vector: Push_back with link

From the cpp documentation for std::vector , I see the following:

 void push_back ( const T& x ); 

I understand that push_back makes a copy of the object I am passing. But why is the signature const T& ? . Looking at this, I initially thought that a link to a const link requires a const link.

+8
c ++ stl
source share
3 answers

Another variant:

 void push_back(T x); 

those. taking x by value. However, this (in C ++ 03) will result in an extra copy of x (copy in push_back arguments). Taking x with a const reference avoids this.

Look at the stack to call v.push_back(T()) , taken by value:

 v.push_back(T()); // instance of T void std::vector<T>::push_back(T x) // copy of T new (data_[size_ - 1]) T(x) // copy of copy of T 

Taking a constant link, we get:

 v.push_back(T()); // instance of T void std::vector<T>::push_back(const T &x) // const reference to T new (data_[size_ - 1]) T(x) // copy of T 

In C ++ 11, it would be possible (albeit unnecessary) to take x by value and use std::move to move to the vector:

 v.push_back(T()); // instance of T void std::vector<T>::push_back(T x) // copy of T new (data_[size_ - 1]) T(std::move(x)) // move the copy of T 
+12
source share

Pressing object is passed by reference to avoid extra copy . Then the copy is placed in vector .

+7
source share

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.

+7
source share

All Articles