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

Checking if the object passed to a method is "this"

本文关键字:对象 是否 this 方法 检查      更新时间:2023-10-16

我正试图解决以下问题:

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

class MyClass {
    //some code here
    void myMethod(MyClass& other) {
        //modify *this and other
    }
}; 

问题是,当调用以下部分时,我希望该方法什么都不做:

MyClass x;
x.myMethod(x);

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

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

我该怎么查?如有任何建议,我们将不胜感激。

您只需比较otherthis:的地址

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

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

您可以检查对象的地址。如果它们相同,返回或抛出异常或其他什么:

class MyClass {
    //some code here
    void myMethod(MyClass& other) {
        if(this==&other){
             //return or throw
        }
        //modify *this and other
    }
}; 

这个简单的

If (&other == this)
    .....your code......

您描述的这些困难类似于编写复制赋值运算符的困难。基本上,在使用完全性能优化的同时,单独的地址检查不足以在出现异常的情况下实现操作的完全正确性。您可以使用"复制并交换"习语中的思想来实现异常安全。

以下是代码示例:

void MyClass::foo(MyClass& other) {
    MyClass tmp(this);
    tmp.add_from(other);
    other.empty();
    swap(tmp, *this);
}

这里交换需要确保永远不会抛出异常。你仍然可以在一开始比较地址,但这只是一个性能优化,而不是实际的安全机制。