Why operator= returns reference not const reference

后端 未结 6 572
轻奢々
轻奢々 2020-12-11 05:29

The original question is related to overloading operator= and I like to share my findings as it was nontrivial for me to find them. I cannot imagine reasonable example to us

6条回答
  •  孤城傲影
    2020-12-11 06:13

    If we consider three auto_ptr a, b and c, the operator = has to return a non-const reference so that you can do multiple assigns since assigning the pointer to another modifies the first.

    so if we have a = b = c, the following happens: c is assigned to b (c is modified to point to null), the operator returns a reference to b the reference returned by (b = c) is assigned to a, it is thus modified to point to null, which is only possible if the reference is non-const.

提交回复
热议问题