Good morning everyone,
Studying a piece of code, I have verified these lines:
Persona& operator=(const Persona& otra)
{
if (this!=otra)
{
delete [] nombre_;
edad_ = otra.edad_;
...
}
}
NOTE: I do not expose the complete code to simplify.
What I would like to know, if the operator overloaded function =
receives an object otra
by reference, the following line:
this != otra
As one would say for formal purposes, what is he achieving?
Because as far as I have understood this is the memory address of the created object, i.e. the memory address of the other object. Compare if the object this
is different from otra
? What is the object this
and what is otra
? Is it the same object you are comparing?
Thank you very much to all.
Effectively,
this
it's a pointer, while itotra
's a reference... That line shouldn't be compileable unless there is an overload of the operator!=
that receives a pointer and a reference:Since I don't think this is the case, I understand that the real intention was for the line to look more like this:
This line is used as a rudimentary method to avoid copying an object over itself which, since there is an object,
delete[]
would imply the irremediable loss of information.Your code looks like the usual case of assignment operator implementation with auto-assignment check.
The auto-assign check is done to prevent assigning an object to itself from having any effect:
In the case of your class
Persona
the problem of auto-assignment is evident, since you delete the content of array 1nombre_
, it would be problematic if the object was saving on itself because you would delete array 1 and then assign the same pointer deleted on itself.Having explained the (possible) motivation behind your code, it must be said that you cannot compare references and pointers 2 (or vice versa). Your code doesn't compile. You are probably missing a
&
:The code above compares two pointers and should not fail unless it
Persona
implements the unary operator&
, to solve that case you can usestd::addressof
.Or are you missing a
*
:The code above compares two instances of the object, but for this to be possible the object must implement the inequality operator
!=
.1 Also known as array, or array in English.
2 Except, if as eferion says , there is some overloaded operator.