C++ - operator= 自赋值检查

C++ - operator= self assignment checking

class Person {
private:
    string name;
    int id;

public:
    Person(string name, int id): name(name), id(id) {}
    const Person& operator=(const Person &another) {
        if (*this == another) // What is the problem here?
            return *this;
        // do copy
        return *this;
    }
};

我想制作一个 operator= 重载函数。在自赋值检查中,如果我像上面那样检查,它会显示错误Invalid operands to binary expression (Person and const Person)。但如果我这样做 this == &another,则不会显示任何错误。
错误是说 this 的类型和 another 的类型不同吗?但如果是这样,为什么 this == &another 会起作用?

*this == another 中,您正在尝试检查两个对象是否具有相同的值。为此,您必须为 Person 定义 operator==。即Person::operator==()会判断两个Person对象是否具有相同的value.

然而,既然你想防止自我赋值,你真正需要的是比较两个对象的 identity——而不是它们的 value 。您可以通过比较它们在内存中的地址来实现这一点,即:

if (this == &another) // Is "another" the same object?
   return *this; // skip assignment

operator== 的操作数是指向 Person 的指针,而不是 Person 对象。

自赋值检查是通过比较两个对象地址

完成的
if (this == &another)

C++ 为相同类型的指针内置了 operator==

您的代码正在比较两个对象的 ,显然您没有为 Person class 定义 operator== .

但是比较值不是正确的做法,因为当您分配两个具有相同值的对象时不需要特殊操作,但有时当您分配两个 相同 个对象。

事实上,在 class 中,您已经证明没有必要进行任何自我分配测试。简单这样就可以了

Person& operator=(const Person &another) {
    name = another.name;
    id = another.id;
    return *this;
}

不要认为测试自赋值可以提高效率,因为自赋值很少见。所以如果你能避免测试,那么通常你应该。

另外值得一提的是,通常首选的赋值方法是 copy and swap idiom,它也不需要任何自我赋值测试。