tinkerbeast
tinkerbeast

Reputation: 2077

No error when taking reference and address of an lvalue

Consider the following code:

int my_func1() { ... }

int& my_func2() { ... }

int* my_func3() { ... }

int main() {

    int a1 = my_func1();         // 1. copy initialisation, rvalue copied to variable
    //int& a2 = my_func1();      // 2. Can't have reference to rvalue 
    const int& a21 = my_func1(); // 3. Can have const reference to rvalue
    //int* a3 = &(my_func1());   // 4. Can't take address of rvalue

    int b1 = my_func2();         // 5. copy initialisation
    int& b2 = my_func2();        // 6. reference initialisation
    int* b3 = &(my_func2());     // 7. HOW IS THIS POSSIBLE?

    int c1 = *my_func3();        // 8. copy initialisation
    int& c2 = *(my_func3());     // 9. HOW IS THIS POSSIBLE?
    int* c3 = my_func3();        // 10. copy initialisation
}

My question is why I am not getting a compiler error for case 7 and 9? - There should be an issue since I am taking a reference to a rvalue or the address of a rvalue.

Also feel free to correct my understating if I got any of the other cases wrong.

Upvotes: 0

Views: 48

Answers (1)

bolov
bolov

Reputation: 75815

(my_func2()) evaluates to an lvalue so you can take its address, i.e. &(my_func2()) is valid.

*(my_func3()) is an lvalue. The dereference operator yields an lvalue, not an rvalue.

Upvotes: 1

Related Questions