What legitimate reasons exist to overload the unary operator&?
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 exist for overloading it?
(Can't say I've ever done that....)
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:
- You have an object which is masquerading as some other object.
- This object can obtain a pointer to the thing it's masquerading as.
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]
.
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.
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
.