Assignment operator with reference class member

前端 未结 3 1613
一向
一向 2021-01-01 13:24

As long as new issues are growing out of my previous question Overloaded assignment operator causes warning about recursion, I was legitimately urged to post this as new one

3条回答
  •  时光说笑
    2021-01-01 14:23

    A C++ 'reference' can only be initialized, not assigned:

    int value1(1), value2(2);
    int& ref1 = value1; // OK
    int& ref2; // compile error: reference not initialized
    int& ref3=ref1; // OK: ref3 refers to the same variable as ref1
    ref1=value2; // equivalent to 'value1=value2'.
    

    Therefor, an object containing a reference can only be initialized, too!

    So indeed: if you need assignment on a class, that class cannot have reference member variables. (as a matter of fact, it could, but the assignment cannot make these members refer to another location)

    When you think about this, it makes sense:

    The reference concept defines 'an alias' for another variable. The aliasing implies that anything you do to your reference, you actually do to the referenced location. When you apply assignment to this alias, actually you assign to the referenced location. The purpose of the reference would be lost if you were able to make it point to a different location using assignment.

    If the latter is what you need, you should use a pointer.

提交回复
热议问题