Why operator= returns reference not const reference

后端 未结 6 565
轻奢々
轻奢々 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:17

    Andrew Koenig wrote a post about this a long time ago. A lot of it comes down to doing what people expect under slight unusual circumstances. The example he gives is that in C, return x=y; always means the same thing as x=y; return x;. In C++, if you return essentially anything other than a reference (including a const reference), the two can mean different things.

    Edit: Sorry, I linked to the wrong post. Try this one. The problem arises from the fact that a T const & can bind to a temporary instead of the "real" object, so what happened with the code above was that it created a temporary, copied the object into it, bound the reference to it, destroyed the temporary, then returned the (now dangling) reference.

提交回复
热议问题