dimanche 17 juillet 2022

C++: rvalues and rvalues reference

I am trying to experiment in C++ the concepts of rvalues and rvalues references. The following code illustrates my approach. I have written 2 foo functions, the first accepting a constant lvalue reference and the second an rvalue reference.

In the main, I call foo with an integer rvalue 2. Since rvalues can bind to constant lvalue references, why is the compiler choosing the second foo function? How does it know which function to use since both accept rvalues ..?

Thanks

void foo(const int& arg){
    std::cout << "foo(const int& arg) called!" << std::endl;
}

void foo(int&& arg){
    std::cout << "foo(int&& arg) called!" << std::endl; 
}

int main(){
   foo(2); // calls the function foo(int && arg), why? 
}

Aucun commentaire:

Enregistrer un commentaire