简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM