c++ references appear reassigned when documentation suggests otherwise

后端 未结 2 1819
孤独总比滥情好
孤独总比滥情好 2021-01-15 15:01

According to this question you can\'t change what a reference refers to. Likewise the C++ Primer 5th Edition states

Once we have defined a reference,

2条回答
  •  [愿得一人]
    2021-01-15 15:46

    You can understand how references work by comparing their behavior to that of a pointer. A pointer can be thought of as the name of the address of a variable; however a reference is just the name of the variable itself--it is an alias. An alias, once set, can never be changed whereas you can assign a pointer a new address if you want. So you have:

    int main(void)
    {
        int a = 2;
        int b = 4;
        int* ptr_a = &a;
        int& ref_a = a;
    
        ptr_a = &b;  //Ok, assign ptr_a a new address
        ref_a = &b;  //Error--invalid conversion.  References are not addresses.
        &ref_a = &b; //Error--the result of the `&` operator is not an R-value, i.e. you can't assign to it.
    
        return 0;
    }
    

提交回复
热议问题