取得左值的引用和地址时没有错误

问题描述 投票:0回答:1

请考虑以下代码:

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
}

我的问题是为什么在案例8和案例9中我没有得到编译器错误?-因为我要引用一个右值或右值的地址,所以应该有一个问题。

如果其他任何错误的情况,请随时纠正我的轻描淡写。

c++ reference rvalue
1个回答
0
投票

解引用运算符求值为左值,而不是右值

© www.soinside.com 2019 - 2024. All rights reserved.