So, I've been studying about std::move()
and I came across l-value and r-value reference and a question popped in my mind -
Consider a code here -:
#include <iostream>
int fun(int arg){
return arg;
}
int main() {
// Write C++ code here
int a=10;
std::cout<<fun(a);
return 0;
}
Now if I want l-value arg to accept r-value I have to declare it const
, like in this case -:
#include <iostream>
int fun(const int& arg){
return arg;
}
int main() {
// Write C++ code here
int a=10;
std::cout<<fun(a);
std::cout<<fun(10); //both will work fine
return 0;
}
But if I do vice-versa i.e. using r-value const
#include <iostream>
int fun(const int&& arg){
return arg;
}
int main() {
// Write C++ code here
int a=10;
std::cout<<fun(a);
std::cout<<fun(10); //throwing error
return 0;
}
Its showing error like -:
cpp:9:20: error: cannot bind rvalue reference of type 'const int&&' to lvalue of type 'int' 9 | std::cout<<fun(a); | ^ /tmp/ufgkAH4KAC.cpp:3:21: note: initializing argument 1 of 'int fun(const int&&)' 3 | int fun(const int&& arg){ | ~~~~~~~~~~~~^~~
Can anyone explain me why?
Aucun commentaire:
Enregistrer un commentaire