I'm studying Copy assignment in C . If you see the line 5 at the code below, there is "this == &rhs". Is this expression legal? this is a pointer to an obejct and rhs is an reference to object. So it is different. Or Can reference be compared with pointer? Thank you.
class Mystring{
//class
};
Mystring& Mystring::operator=(const Mystring &rhs){
if (this==&rhs) //<===========this line
return *this;
delete [] str;
str = new char[std::strlen(rhs.str) 1];
std::strcpy(str, rhs.str);
return *this;
}
CodePudding user response:
there is "this == &rhs". Is this expression legal?
Yes.
this is a pointer to an obejct and rhs is an reference to object. So it is different.
Yes.
Or Can reference be compared with pointer?
Potentially yes (if the reference is to a class type with an operator overload for comparing with a pointer), but that's not what the example program does because it doesn't compare pointer with rhs
. The example programs a pointer with &rhs
which is also a pointer.
CodePudding user response:
there is "this == &rhs". Is this expression legal?
Yes it is.
Just a sidenote, References are aliasses to another variable.
Also a quick optimization of the code below:
Mystring& Mystring::operator=(const Mystring &rhs){
if (this != &rhs)
{
delete [] str;
str = new char[std::strlen(rhs.str) 1];
std::strcpy(str, rhs.str);
}
return *this;
}