c++ references appear reassigned when documentation suggests otherwise

后端 未结 2 1804
孤独总比滥情好
孤独总比滥情好 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:43

    You are not reassigning a reference. A reference acts as an alias for a variable. In this case, ref is an alias for a, so

    ref = b;
    

    is the equivalent of

    a = b;
    

    You can easily check that by printing out the value of a:

    std::cout << a << std::endl; // prints 4
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题