0

I had start learning about the move semantics and come to know about rvalue references.

So, wanted to ask why do we need rvalue references if things can still work with references or simple call by value.

#include <iostream>

void func(int x){
     std::cout<<x<<std::endl;
     x += 1;
}

void func_ref(int &x){
  std::cout<<x<<std::endl;
  x += 1;
}

void func_rref(int &&x){
  x += 1;
  std::cout<<x<<std::endl;
}
int main() 
{
    int x = 1;
    func(x);//1
    x += 1;
    func(x);//2
    func_ref(x);//2
    std::cout<<x<<std::endl;//3
    
    func_rref(2);
    return 0;
}

What's the use of this func_rref function how this is different from normal func where parameter passed as value or if parameter passed as reference ?

Fedrick
  • 23
  • 5
  • See dupe: [Pass by value vs pass by rvalue reference](https://stackoverflow.com/questions/37935393/pass-by-value-vs-pass-by-rvalue-reference) and [When to use rvalue reference](https://stackoverflow.com/questions/62175820/when-to-use-rvalue-reference) – Jason Dec 05 '22 at 08:50
  • Not much of a profit with a single integer in a hello-world application. But if you have to work with millions of values each second, rvalue references will give better performance by reducing copying of data – Alexey S. Larionov Dec 05 '22 at 08:51
  • your example is missing an actual comparison of calling the functions with same arguments. Try `func_ref(2);` and you will see the difference – 463035818_is_not_an_ai Dec 05 '22 at 08:52
  • @AlexeyLarionov moving millions of `int` will still be the same as copying them. – 463035818_is_not_an_ai Dec 05 '22 at 08:53

0 Answers0