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
const
object 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&&)
because9
is anint
prvalue and not aconst int
prvalue. Note also that for aconst int
prvalue, itsconst
will 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
const
prvalues the second version of the functionprint
withprint(const C&&)
will be selected unlike the built in typeint
as demonstrated below.The output of the above program for class type
C
is:As is evident from the above example, for class types the second version of print with
const C&&
will be selected.