复制赋值运算符=自赋值检查错误

时间:2013-12-09 19:54:20

标签: c++

如果我有一个用

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

并像这样定义自我分配检查

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

然后g ++发出错误:

  

错误:‘operator!=’不匹配(操作数类型为‘Person’‘const Person')

但是如果我将其改为

Person & operator=(Person& other);

然后g ++发出错误:

  

错误:‘operator!=’不匹配(操作数类型为‘Person’‘Person’

为什么,在第二种情况下,如果类型相同则不匹配?

后续问题:

为什么只有这项检查才有效?

if (this != &other)

2 个答案:

答案 0 :(得分:3)

此检查不正确:它不是检查指针,而是检查实例,调用operator !=(other)

您应该将行更改为

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

这样您就可以检查对象的“身份”,而不是检查相等性。检查指针的相等性非常快,但更重要的是,这是正确的做法。检查背后的重点是避免破坏对象的内容以准备将数据复制到其中,只是发现您刚刚删除了自己的数据。

答案 1 :(得分:2)

类型是相同的并不重要。无论运营商是否未定义,都很重要。编译器不为您提供默认的operator!=,显然您自己没有定义它。

但在这种情况下:

if (this != &other)

这是有效的,因为它是一个指针比较。指针比较是一种内置功能,可用于任何指针类型。