So I wrote a code in C++ 11
#include <iostream>
using namespace std;
void print (int &&a)
{
cout<<"rval ref";
}
void print (const int& a)
{
cout<<"const ref";
}
int main()
{
print(9);
}
The output of code was fascinating that it is "rval refernce" But if I rewrite the code just removing a function defination:
#include <iostream>
using namespace std;
void print (const int& a)
{
cout<<"const ref";
}
int main()
{
print(9);
}
I get output as "const ref"
Edit: There's one more thing here if I rewrite code again as
#include <iostream>
using namespace std;
void print (int &&a)
{
cout<<"rval ref";
}
void print (const int&& a)
{
cout<<"const ref";
}
int main()
{
print(9);
}
Still its printing "rval ref" , please explain the logic
Can someone explain why C++ give preference to && over const while passing a ravlue as argument ?## Heading ##
Lets see on case by case basis what is happening:
Case 1
Here we consider:
The behavior of this case 1 can be understood from over.ics.rank which states:
(emphasis mine)
This means that in your this case 1, the version with
int&&is preferred overconst int&.Case 2
Here we consider:
Here in case 2, since an lvalue reference to
constobject is allowed to bind to an rvalue, the providedprint(const int&)is viable and is the only one available and hence is selected.Case 3
Here we consider:
Now, this chooses the first version
print(int&&)because9is anintprvalue and not aconst intprvalue. Note also that for aconst intprvalue, itsconstwill be stripped off before any further analysis and so the first versionprint(int&&)will be selected. This is as specified in expr#6:This means that for class type
constprvalues the second version of the functionprintwithprint(const C&&)will be selected unlike the built in typeintas demonstrated below.The output of the above program for class type
Cis:As is evident from the above example, for class types the second version of print with
const C&&will be selected.