Comparing pointers for self-assignment
I am trying to overload the = operator on a simple C++ class called Set that contains a dynamic array of ints. For the = operator, I first want to check for self assignment, so I wanted to c开发者_如何学Compare 2 pointers to make see if they have the same memory address. Here's the code:
Set& Set::operator=(const Set& setEqual)
{
//first check for self assignment
if(setEqual == this*)
cout << "this is self assignment";
}
The error spat out is error: expected primary-expression before ')' token
I believe I'm having a misunderstanding of pointers again, so if anyone could point (ha!) me in the right direction, I'd appreciate it.
The error is becuase this*
is not valid - *
is either infix (in multiplication) or prefix (in dereferencing pointers).
You probably want &setEqual == this
- that is assigning from an object at the same memory address or setEqual==*this
- comparing equality using whatever operator==
you have defined
To detect self-assignment you need
if(&setEqual == this)
you should never use
if(setEqual == *this)
for detecting self-assignment as the latter statement will invoke comparison of the objects, which might be overloaded in the way you don't expect and is likely slower as well.
If you want to compare the address of the thing pointed too you really want this:
Set& Set::operator=(const Set& setEqual)
{
//first check for self assignment
if(&setEqual == this)
cout << "this is self assignment";
}
Using (setEqual==*this)
as sugested by some of the solutions compares if the objects are equal under operator==
.
精彩评论