3

From c++11 onwards, there are lvalue and rvalue references. I am aware of the differences between them. However, akin to function pointers such as int(*fptr)(), c++ also has lvalue and rvalue references to functions int(&lvalue)() and int(&&rvalue)(), and there doesn't appear to be any difference in this case. What is the difference between them, and when should I use which one?

The following code runs the same thing using lvalue and rvalue references. There doesn't appear to be a difference, and they seem to be able to be used interchangeably as function parameters as well.

#include<cstdio>
int add(int x){return x+1;}
int runLvalue(int(&input)(int),int val){
    return input(val);
}
int runRvalue(int(&&input)(int),int val){
    return input(val);
}
int main()
{
    int(&lval)(int)=add;
    int(&&rval)(int)=add;
    printf("%d %d %d %d %d %d",
        runLvalue(lval,8),
        runRvalue(lval,9),
        runLvalue(rval,0),
        runRvalue(rval,4),
        lval(5),
        rval(1));
    return 1;
}

This outputs 9 10 1 5 6 2 as expected, and doesn't appear to show any reason to use one type of function reference over the other.

  • Such a questions was asked a week ago. – 273K Apr 25 '23 at 13:21
  • your two functions do just the same. If you use function pointers, you can write two overloads of the same function to actually do something different. https://godbolt.org/z/zvxdT1EPT – 463035818_is_not_an_ai Apr 25 '23 at 13:24
  • 1
    @273K [this](https://stackoverflow.com/questions/76031528/in-c-why-can-both-function-left-and-right-references-be-bound-to-function-nam) perhaps? – Jason Apr 25 '23 at 13:52
  • @463035818_is_not_a_number that's an lvalue and rvalue reference to a function **pointer**. Not the same. – user253751 Apr 25 '23 at 13:56
  • @user253751 yes i know. Nevertheless I was wondering what OP expected to be different when `runLvalue` and `runLvalue` just do exactly the same – 463035818_is_not_an_ai Apr 25 '23 at 13:59
  • @Jason Yes, it's. I remembered that question after my failed attempt to answer. Technically, it could be also closed as a duplicate. – 273K Apr 25 '23 at 14:02

0 Answers0