C++ Return value, reference, const reference

前端 未结 5 1506
花落未央
花落未央 2020-12-12 14:06

Can you explain to me the difference between returning value, reference to value, and const reference to value?

Value:

Vector2D oper         


        
5条回答
  •  感情败类
    2020-12-12 14:57

    There is no difference unless you write something weird like

    (v1 += v2) = v3;
    

    In the first case, the assignment will be to a temporary, and the overall effect will be v1 += v2.

    In the second case, the assignment will be to v1, so the overall effect will be v1 = v3.

    In the third case, the assignment won't be allowed. This is probably the best option, since such weirdness is almost certainly a mistake.

    Why returning of reference is better than returning of value?

    It's potentially more efficient: you don't have to make a copy of the object.

    and why returning of const reference is better than returning of not-const reference?

    You prevent weirdness like the above example, while still allowing less weird chaining such as

    v1 = (v2 += v3);
    

    But, as noted in the comments, it means that your type doesn't support the same forms of (ab)use as the built-in types, which some people consider desirable.

提交回复
热议问题