user3084186
user3084186

Reputation: 23

copy assignment operator= self-assignment check error

If I have a class declared with

class Person
{
  public:
    Person(const int age);  // constructor
    Person(const Person & other);
    Person & operator=(const Person & other);  // copy assignment operator=
    ~Person();
};

and define self-assignment check like this

Person & Person::operator=(const Person & other)  // copy assign operator=
{
  if (*this != other)
  {... copy data ...}
  return *this;
}

then g++ issues an error:

error: no match for ‘operator!=’ (operand types are ‘Person’ and ‘const Person’)

But then if I change it to

Person & operator=(Person& other);

then g++ issues an error:

error: no match for ‘operator!=’ (operand types are ‘Person’ and ‘Person’)

Why, in the second case, no match if types are the same?

And a followup question:

Why only this check is considered valid ?

if (this != &other)

Upvotes: 2

Views: 531

Answers (2)

Benjamin Lindley
Benjamin Lindley

Reputation: 103703

It doesn't matter that the types are the same. It matters whether or not the operator is not defined. The compiler does not provide a default operator!= for you, and apparently you haven't defined it yourself.

In this case, however:

if (this != &other)

This is valid because it is a pointer comparison. Pointer comparison is a built-in feature that is available to any pointer type.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

This check is incorrect: rather than checking the pointer, it checks the instance, calling the operator !=(other).

You should change the line to

if (this != &other) {... copy data ...}

This way you would check the "identity" of your object, rather than checking the equality. Checking equality on pointers is very fast, but more importantly, that's the right thing to do. The whole point behind the check is to avoid destroying the content of your object in preparation to copying the data into it, only to find that you have just deleted your own data.

Upvotes: 4

Related Questions