复制赋值运算符返回 *this vs (*this)

Copy assignment operator returning *this vs (*this)

有区别吗

class MyString {
...
    MyString &operator=(MyString other) {
        swap(s, other.s);
        return (*this);
    }
};

class MyString {
...
    MyString &operator=(MyString other) {
        swap(s, other.s);
        return *this;
    }
};

我在其他 中读到,添加括号表示您 return 通过引用而不是值。但是如果定义了 return 类型,它似乎没有什么区别。

您引用的 link 讨论了不同的情况。在这种情况下

*this == (*this)

这取决于您的偏好,因为它们都将做完全相同的事情。就个人而言,我更喜欢 *this 以避免不必要的括号

Operator precedence 有时可以改变您想要取消引用某些内容的方式。想象一下这种情况

*my_vector[0]

你认为这里会发生什么?是在干嘛

(*my_vector)[0]

或者

*(my_vector[0])

正确答案是第二个。有时您可能想改变这种行为,这就是 () 来的时候。