2
votes

There two declarations for std::vector::push_back.I understand rvalue and lvalue to some degree. As far as i know, almost all types(T&、T&&、T) could be converted to const T&, so which one does the compiler choose when different types of object passed to std::vector::push?

I am a novice in C++.Though i thought over and over, i still could not get the idea.It would be better if you could give me some simple examples to make it clear.I would be greateful to have some help with this question.

As per the documatation(http://www.cplusplus.com/reference/vector/vector/push_back/), which says that:

void push_back (const value_type& val);

void push_back (value_type&& val);

Adds a new element at the end of the vector, after its current last element. The content of val is copied (or moved) to the new element.

1

1 Answers

5
votes

Lvalues cannot be bind to rvalue referneces, which implies, that when you invoke std::vector<T>::push_back with an lvalue argument, the only viable overload is that with const T& parameter.

Rvalues can be bind to both rvalue references and const lvalue references. Therefore, both overloads are applicable. But according to the C++ overload rules, the overload with rvalue reference parameter T&& will be selected.


You can easily try this by yourself:

void f(const int&) { std::cout << "L"; }
void f(int&&) { std::cout << "R"; }

int main() 
{
   int i = 0;
   f(i);  // prints "L"
   f(0);  // prints "R"
}