Нет ошибок при получении ссылки и адреса lvalue - PullRequest
0 голосов
/ 09 апреля 2020

Рассмотрим следующий код:

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
}

У меня вопрос, почему я не получаю ошибку компилятора для случаев 7 и 9? - Должна быть проблема, так как я принимаю ссылка на rvalue или адрес rvalue.

Также не стесняйтесь исправить мое занижение, если я ошибся в любом другом случае.

1 Ответ

1 голос
/ 09 апреля 2020

(my_func2()) соответствует lvalue, поэтому вы можете взять его адрес, т. Е. &(my_func2()) является действительным.

*(my_func3()) является lvalue. Оператор разыменования выдает lvalue, а не rvalue.

...