From the cpp documentation for std::vector, I see this:
void push_back ( const T& x );
I understand that push_back makes a copy of the object that I pass. But, why is the signature const T& ? By looking at this, I initially thought it takes a const reference of whatever object that I push to the vector.
The other option would be
that is, taking
xby value. However, this would (in C++03) result in creating an extra copy ofx(the copy in the arguments topush_back). Takingxby const reference avoids this.Let’s look at the stack for a call
v.push_back(T())taken by value:Taking by const reference we get:
In C++11 it would be possible (though unnecessary) to take
xby value and usestd::moveto move it onto the vector: