Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++: implementing the equal method - how to make sure the given object is not the same reference as this?

Tags:

c++

Consider the following code snippet:

bool SomeObject::equal(const SomeObject& rhs) const
{
  if (this == &rhs)
  {
    return true;
  }

  // check the state
}

The problem with this code is that SomeObject might override operator& (or someone might add it in the future), which in turn may break this implementation.

Is it possible to test whether rhs and *this are the same object without being at the mercy of operator& implementation?

like image 643
mark Avatar asked Jan 11 '12 15:01

mark


People also ask

How do you check whether two objects are of the same instance?

If you just want to know wether two objects denode the same memory cell, so they are really the same, you cann use the equals operator: Object A = new Fruit("A"); Object B = new Fruit("A"); System. out. println(A == B);

What is the most accurate way to check for equality by reference?

To check for reference equality, use ReferenceEquals. To check for value equality, use Equals or Equals. By default, the operator == tests for reference equality by determining if two references indicate the same object, so reference types do not need to implement operator == in order to gain this functionality.

How do you know if an Object is equal?

Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity. For example, the expression obj1==obj2 tests the identity, not equality.


2 Answers

If you want to get the actual address of the object and ignore overloaded & operators then use std::addressof

bool SomeObject::equal(const SomeObject& rhs) const
{
  if (this == std::addressof(rhs))
  {
    return true;
  }

  // check the state
}

Reference: http://en.cppreference.com/w/cpp/memory/addressof

like image 122
JaredPar Avatar answered Nov 15 '22 12:11

JaredPar


There's a std::addressof function in C++11 which should do what you want.

If you wanted to implement it yourself, you could use casting to another type:

(SomeClass*)&reinterpret_cast<char&>(rhs)

However, I wouldn't bother; a const equals function should work fine for identical parameters.

like image 23
jpalecek Avatar answered Nov 15 '22 12:11

jpalecek