Why would anyone want to overload the & (address-of) operator? [duplicate]
Asked Answered
F

4

25

Possible Duplicate:
What legitimate reasons exist to overload the unary operator& ?

I just read this question, and I can't help but wonder:

Why would anyone possibly want to overload the & ("address-of") operator?

SomeClass* operator&() const {
    return address_of_object;
}

Is there any legitimate use case?

Flatus answered 27/6, 2011 at 22:7 Comment(3)
@Matti: We can flag for merge. That's better than duplicating the answers as well as the question.Confederate
@Tomalak: Whoa. I didn't know that was possible.Papist
@Matti: I'm not 100% convinced that it is, but I've heard rumours... :)Confederate
C
35

If you're dealing with any sort of wrapper objects, you might want or need to transparently forward the access to the wrapper to the contained object. In that case, you can't return a pointer to the wrapper, but need to overload the address-of operator to return a pointer to the contained object.

Conure answered 27/6, 2011 at 22:11 Comment(1)
Heh, I searched for "c++ overload address of" exactly to find out whether I can do this. Thanks for the extremely quick reassurance :-)Trip
A
8

Because they're evil and want you to suffer.

Or I guess if you are using proxy objects? I suppose you might want to return a pointer to the managed object instead of the container - although i'd rather do that with a getter function. Otherwise you'd have to remember to use things like std::addressof.

Areca answered 27/6, 2011 at 22:9 Comment(1)
I guess the point of a proxy object is that you don't know it's there. (Or you act as if you didn't knew.) In particular, you don't know about it's address. It's usually a temporary anyway.Bluebeard
A
8

Yes, for debugging (if you want to trace any access or reference, you might want to put a log line on any call to &, * or ->).

Albumin answered 27/6, 2011 at 22:10 Comment(0)
N
0

I have seen this in productive code already.

But there, a binary representation of the content of a struct was returned, not just 0.

And the usecase was simple: Binary operations.

Natheless answered 27/6, 2011 at 22:13 Comment(3)
Binary operations with unary &?Confederate
I will look if i find the code again, then i'll post an example. Sounds strange, looks funny ( i think ugly) but maybe the author thought its nicer to use the & twice ;)Natheless
because why have it do something that makes sense, when you can instead do... that. :/Trip

© 2022 - 2024 — McMap. All rights reserved.