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?
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);
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With