Recently i accidently programmed the following:
void someFunction(const SomeClass&& value){
//Some Code
}
I didn't mean to add the 'const' keyword to the value parameter. However, this made me think: is it even possible to somehow call this function, if an equivalent function without const exists? If yes, does this ever make sense and is there some practical use to it?
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;
}
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. [...]