Why would anyone want to overload the & (address-o

2019-03-18 02:47发布

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?

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

Is there any legitimate use case?

4条回答
孤傲高冷的网名
2楼-- · 2019-03-18 03:00

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.

查看更多
叼着烟拽天下
3楼-- · 2019-03-18 03:18

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.

查看更多
男人必须洒脱
4楼-- · 2019-03-18 03:21

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 boost::addressof.

查看更多
可以哭但决不认输i
5楼-- · 2019-03-18 03:24

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 ->).

查看更多
登录 后发表回答