0

I was reading about the make_pair() template function in C++, and couldn't understand why its parameters are rvalue reference variables. Why shouldn't they accept lvalues as well, like a normal variable?

template <class t1, class t2>
pair<v1, v2> make_pair (t1&& x, t2&& y);

What is the use of using rvalue reference variables here?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 6
    "*its parameters are rvalue reference variables*" - no, that is incorrect. They are actually [**forwarding references**](https://en.cppreference.com/w/cpp/language/reference#Forwarding_references). They will accept either lvalues or rvalues depending on what the caller actually passes in. "*Why shouldn't they accept lvalues as well*" - they DO accept lvalues. – Remy Lebeau Jun 21 '22 at 22:38
  • 2
    Related: https://stackoverflow.com/questions/45996187/c-forwarding-reference-and-r-value-reference https://stackoverflow.com/questions/46213764/rvalue-reference-or-forwarding-reference – Jerry Jeremiah Jun 21 '22 at 22:39
  • 2
    The short answer to this question is that rvalue references and "universal references" (as shown here) allow you to avoid unnecessary copies and moves, which was a major source of inefficiency in older versions of C++. I strongly recommend you find a good source on perfect forwarding and read up a bit. There are quite a few. [Here's one](https://eli.thegreenplace.net/2014/perfect-forwarding-and-universal-references-in-c) that's pretty popular. – Jon Reeves Jun 21 '22 at 23:10
  • @JonReeves the official term is "forwarding reference", not "universal reference". https://stackoverflow.com/questions/39552272/ – Remy Lebeau Jun 21 '22 at 23:42
  • Take that Scott Meyors ... – Fantastic Mr Fox Jun 21 '22 at 23:47
  • Thanks @RemyLebeau, actually wasn’t aware the term had been formalized. I’ll update my response. – Jon Reeves Jun 21 '22 at 23:50
  • Just kidding, time window exceeded. ::shrug::: – Jon Reeves Jun 21 '22 at 23:56

0 Answers0