Home > OS >  Should you return a reference using operator for adding two classes together?
Should you return a reference using operator for adding two classes together?

Time:12-08

From the examples I have seen when people use the operator when adding two instances of a class, the usual pattern is to return an object. Suppose we have a Vector class with attributes u and v, an implementation of operator could be,

Vector2 Vector2::operator (const Vector2& other) {
    return Vector2(this->u   other.u, this->v   other.v);
}

Why is the standard pattern not to return a reference? This is returning an object that was created on the Stack, this means that it should be garbage collected later on when we leave the function and could lead to problems from what previously pointed to it. e.g.

Vector2 v = Vector(10,20) Vector(30, 40), would v later be pointing to a garbage collected variable? Because the result of Vector(10, 20) Vector(30, 40) was created on a Stack (That we have now left).

What I am saying is, why should this not be something like,

Vector2* Vector2::operator (const Vector2& other) {
    return new Vector2(this->u   other.u, this->v   other.v);
}

CodePudding user response:

Should you return a reference using operator for adding two classes together?

No.

Why is the standard pattern not to return a reference?

Because the binary operator conventionally returns a new object.

Vector2 v = Vector(10,20) Vector(30, 40), would v later be pointing to a garbage collected variable?

No. C has no garbage collector, and Vector2 is presumably not a pointer.

What I am saying is, why should this not be something like,

Vector2* Vector2::operator (const Vector2& other) {
    return new Vector2(this->u   other.u, this->v   other.v);
}

Because:

  1. Using bare owning pointers is a horrible idea.
  2. Returning bare owning pointer makes the idea even worse.
  3. Operator overloads that represent the abstract operation as the fundamental operation (for example, addition in this case) should conform to the same interface and behaviour as the fundamental operation.
    • The type of 1 1 is not int*, and so the type of vector vector shouldn't be Vector2*.
    • There is no need to delete the result of 1 1 and so there shouldn't be a need to delete the result of vector vector.
  • Related