Can you explain to me the difference between returning value, reference to value, and const reference to value?
Value:
Vector2D operator += (const Vector2D& vector)
{
this->x += vector.x;
this->y += vector.y;
return *this;
}
Not-const reference:
Vector2D& operator += (const Vector2D& vector)
{
this->x += vector.x;
this->y += vector.y;
return *this;
}
Const reference:
const Vector2D& operator += (const Vector2D& vector)
{
this->x += vector.x;
this->y += vector.y;
return *this;
}
What is the benefit of this? I understand the sense behind const reference passing to function as you want to make sure not to modify this value on which reference is pointing to inside a the function. But I'm confused by the meaning of returning const reference. Why returning of reference is better than returning of value, and why returning of const reference is better than returning of not-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.