Okay, I\'ve been inspired to do some head punching. Seems like overloading operator&
leads to not a small amount of pain.
What legitimate cases exis
I seem to remember something like a smart pointer class which overrode operator&
because it wanted to return the address of the contained pointer rather than the address of the smart pointer object. Can't remember where I saw it or whether it seemed like a good idea at the time.
Aha, remembered: Microsoft's CComPtr.
Edit: To generalize, it might make sense under the following conditions:
Returning anything other than a legitimate pointer would violate the principle of least astonishment.
It is useful when representing the &
operation in lambda placeholder notation, e.g. &_1[_2]
.
You can overload the address operator to make it private. This could be useful for implementing some sort of baton passing scheme, where the address of the baton cannot be taken. If the baton's constructors are hidden, this can keep the baton's scope airtight.
I've done this to good effect in the context of a DSL that generates LLVM code. An example will illustrate. Say x
and y
are values (i.e., objects of type value
). Then the expression x+y
emits an ADD instruction into some code stream. Quite sensibly, the expression &x
emits an instruction to take the address of x
.
Once I used to override operator & (without altering its behavior) as private to the class, in order to protect against occasional creation of smart pointer to the object created in the stack. Still not sure if it was really good idea...
Overloading unary &
makes your object behave like a reference (in that respect).
I'm pretty sure that it's a fool's errand to attempt to provide alternatives to built-in references, in particular since references aren't objects at all in C++, and they don't have their own addresses. Instances of your user-defined type inevitably are objects, and do have addresses, even if you disable the normal way of obtaining that address. So it is never a perfect imitation.
But, people are very keen on user-defined alternatives to pointers, so I can sort of see how someone might want to attempt it. I'm not sure they'll avoid creating a type that (mis)behaves in ways that will make its users wish they hadn't bothered.