检查传递给方法的对象是否为"this"

Jyt*_*tug 0 c++ methods class

我正在尝试解决以下问题:

假设我正在编写一个类,它有一个myMethod修改两者的方法*this和传递的参数:

class MyClass {
    //some code here
    void myMethod(MyClass& other) {
        //modify *this and other
    }
}; 
Run Code Online (Sandbox Code Playgroud)

问题是,当调用以下部分时,我希望该方法不执行任何操作:

MyClass x;
x.myMethod(x);
Run Code Online (Sandbox Code Playgroud)

检查相等是不够的,因为我希望能够为两个相同的对象调用它.

例如,以一种更为实际的方式,假设它MyClass是类似的std::set并且myMethod合并两个集合,清空other.可以合并两个相同的集合,但我显然不能清空并同时填充一个集合.

我该如何检查?任何建议将被认真考虑.

Tar*_*ama 6

你可以只是比较的地址otherthis:

class MyClass {
    //some code here
    void myMethod(MyClass& other) {
        if (this != &other) {
            //modify *this and other
        }
    }
}; 
Run Code Online (Sandbox Code Playgroud)

由于您通过引用传递,如果将相同的对象传递给您调用它的函数,则指针将是相等的.

  • @SergeyA我想你在谈论复制和交换习语,但这并不是一回事(尽管我并没有贬低你). (2认同)