Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is `this == &x` the correct way to determine if a pointer (this) and a reference (x) point to the same object?

I have a class, and inside this class, a function that takes as argument another instance of the same class. Inside this function I need to do some stuff, but only if the argument passed is not the same instance as the current one. Is the following code the correct way to do this?

class Foo
{
    void Foo::func(Foo &other)
    {
        if (this != &other)
            // do stuff
    }
}
like image 228
becko Avatar asked Oct 02 '22 12:10

becko


1 Answers

Yes, (ptr == &ref) is the correct way of determining whether the pointer and reference are to the same object. (Technically it might fail, if operator& is overloaded, but that's a pretty unlikely situation, and one you'd obviously already be aware of, as the author of the class.)

like image 53
Sneftel Avatar answered Oct 05 '22 12:10

Sneftel