I am performing the operator overload = for a Rational data type. That is, for this to work with the Rational type:
res = p;
According to the book I'm following, it tells me to do it with the = operator as a member function (method) and:
- Receive a type by reference.
- That I create an object with the copy constructor, passing it as a parameter the object received in said function.
- Let it swap that created object for the *this.
- Which returns *this.
Implementing it, and working there are no problems (it works perfectly) with the version I have made, which would be this (correct me if it is not correct):
Racional& Racional::operator=(const Racional& der)
{
Racional auxiliar(der);
this->numerador = auxiliar.obtenerNumerador();
this->denominador = auxiliar.obtenerDenominador();
return *this;
}
My question is the following. Why do I have to create a helper object if I can directly do:
Racional& Racional::operator=(const Racional& der)
{
this->numerador = der.obtenerNumerador();
this->denominador = der.obtenerDenominador();
return *this;
}
Thank you very much for everything comrades.
In my opinion the question should be " Why should I adopt a specific solution in this specific case? ".
In the assignment operator (and its evil twin, the move operator) there is no single solution or pattern that is always valid, each data type may require a different solution.
The copy-swap idiom.
As you have well commented, in the specific case of your type
Racional
you do not have any need for an auxiliary object. The auxiliary may be mentioned as part of the copy swap idiom .The copy-swap idiom consists of delegating the functionality of assigning new values to the copy constructor, by creating a local copy of the data that will then be exchanged with the current data; then the temporary object (containing the old data) is destroyed. It is precisely the idiom that Trauma has used in his response From him:
Is the assistant necessary?
The copy-swap idiom uses a helper to ensure that the object's destructor is called for the data being discarded; this is relevant in cases where the object manages resources:
If in the previous example the assignment operator had been this:
We would lose the original pointer
i
, causing a memory leak. But it's not your case, your classRacional
doesn't manage resources so you don't need to use the copy-swap idiom.Conclusion.
C++ allows overloading operators so that we can take care of special tasks that an object may require when operated on; This customization of behavior is special in each case and although there are certain idioms we should not use them without considering whether they fit the specific needs of each case.
In your case, your question is relevant and correct; the answer is: you don't need the temp... but DO NOT consider this answer set in stone, in other situations the answer could be different.