C++ Return value, reference, const reference

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.

Leave a Comment