mercredi 19 décembre 2018

i used int && and used is function for lvalue not for rvalue [duplicate]

This question already has an answer here:

I started to learn about reference to rvalue. I am trying to understand my code, but I do not understand one line, why is used function for lvalue, not rvalue.

#include <iostream>
void reference_fun(int &k) {
  std::cout << "reference to lvalue (object) = " << k << std::endl;
}

void reference_fun(int &&k) {
  std::cout << "reference to rvalue (temporary) = " << k << std::endl;
}

void test2(int &&k) {

  //rvalue in the body of the function becomes lvalue
  reference_fun(k);
  reference_fun(std::move(k));
}

int main() {
  int obj = 10;
  int &&rvalue = 10 + 10;
  reference_fun(obj);                                                     /* result as function to lvalue */
  reference_fun(321);                                                     /* result as function to rvalue */
  reference_fun(321 + 3);                                                 /* result as function to rvalue */
  reference_fun(rvalue); // I don't understand the result of this line, why is used function to lvalue, when rvalue is int && ?
  test2(14 + 10);                                                         /* result as function to lvalue and rvalue */
  // test2(rvalue); //compilation error
  return 0;
} 

This is my output:

reference to lvalue (object) = 10
reference to rvalue (temporary) = 321
reference to rvalue (temporary) = 324
reference to lvalue (object) = 20 //this line ?
reference to lvalue (object) = 24
reference to rvalue (temporary) = 24

I have a question about this line : reference_fun(rvalue); Why is used void reference_fun(int &k); but not void reference_fun(int &&k);, when I defined rvalue as int&& ?

Aucun commentaire:

Enregistrer un commentaire