Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...