0

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?

Brotcrunsher
  • 1,964
  • 10
  • 32
  • http://www.codesynthesis.com/~boris/blog/2012/07/24/const-rvalue-references/. "Specifically, a const rvalue will prefer to bind to the const rvalue reference rather than the const lvalue reference." But, you shouldn't bother with const rvalues. They don't make much sense. –  May 05 '17 at 22:10

1 Answers1

2

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. [...]

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • See the comment on the linked article for more information on why with `int` it uses the non-`const` overload: *"There are no const prvalues of scalar types. For a const rvalue you either need an Xvalue and/or a class-type object. I’m almost sure that a conforming compiler would treat f(g()) just like f(1) in terms of overload resolution since g just returns a value and not an object."* – clcto May 05 '17 at 22:20
  • @clcto thanks for the clarification – 463035818_is_not_an_ai May 05 '17 at 22:21