I am refactoring a legacy code. I have to compare a pointer with reference for equality (To check whether both objects are equal). This question in SO does it by comparing the address. if I do the same for pointer and reference as below, would there be any issues (any exceptional cases?). So far in my testing, it's working properly. Please advice
#include <stdio.h>
#include <iostream>
class MemberData
{
//Huge class with many data members
};
int main()
{
MemberData x ;
const MemberData& y = x;
MemberData *ptr= &x;
if(std::addressof(*ptr)==std::addressof(y))
{
std::cout << "Both are equal" << "\n";
}
return 0;
}
std::addressof(*ptr)
seems redundant. If you have a pointer to the object, and you need a pointer to the object, then why indirect through the pointer and then get the pointer to object that was being pointed at? ptr == std::addressof(y)
should work just as fine. As long as you want to compare equality of the address...
(To check whether both objects are equal)
Comparing equality of addresses is comparing identity, i.e. whether they are the same object. To compare equality of objects, you'd generally compare their value. For example, following variables are not the same object and thus do not have the same address, but they are equal in value (assuming sane copy constructor):
MemberData x;
MemberData y = x;