This code:
#include <iostream>
using namespace std;
struct s{};
void someFunction(s& value){ std::cout << "ref" << std::endl; }
void someFunction(const s&& value){ std::cout << "const" << std::endl; }
void someFunction(s&& value){ std::cout << "non const" << std::endl; }
const s foo() { return s(); }
s bar() { return s(); }
int main() {
someFunction(bar());
someFunction(foo());
return 0;
}
Prints
non const
const
For some explanation (that I cannot provide ;) I refer you to this site. The most relevant quote is:
[...] This makes const rvalue references pretty useless. Think about it: if
all we need is a non-modifiable reference to an object (rvalue or
lvalue), then a const lvalue reference does the job perfectly. The
only situation where we want to single out rvalues is if we want to
move them. And in that case we need a modifiable reference.
The only use case I could imagine is to use someFunction
to detect whether a second function returns a const
or a non-const
, but I guess there are easier ways to find that out.
As a sidenote: When you replace s
with int
in above code it prints:
non const
non const
and that is because (quoting from the same site, comment from pizer):
There are no const prvalues of scalar types. For a const rvalue you
either need an Xvalue and/or a class-type object. [...]