How do I decide whether I need addressof(x)
instead of &x
when taking the address of an object?
Seems like the question was confu
If it's a user-defined type with overloaded unary operator&
, and you want its address, use addressof
.
I'd say you should always use &
because, as you say, if you don't, it defeats the purpose of the overload. Unless of course you do something meaningful with the overload, in which case you'd need addressof
(outside the class, inside you can just use this
), but you have to be very certain of what you're doing.
Here's more - if you want to overload operator&
outside the class (you can), you have to use addressof
to return the address, otherwise it results in infinite recursion:
struct Class
{
virtual ~Class() {}
int x;
};
void* operator&(const Class& x)
{
//return &x; <---- infinite recursion
return addressof(x) + 4; //I know this isn't safe
//but I also know the intrinsics of my compiler
//and platform to know this will actually return
//the address to the first data member
}
I know this isn't safe.