Does it make sense to overload the unary operator &?

Thus, C ++ allows you to overload the unary operator & (address). Do you know of any real world example when operator & was rightfully overloaded? And the second, more specific question: did you know about any real world when operator & was rightfully overloaded while preserving the address semantics? TIA

+4
source share
6 answers

I have 207 real examples of operator &() : Code Search 1 , Code Search 2 .

Including SafeInt<> (to get the base integer), boost :: gil (apparently also for getting raw data), Mozilla (say, "it's risky to define the & operator, but hey, we know what we're doing." ), wxWidgets, Armagetron, and more.

It seems that the idiom &*it iterator is used to get the source link or pointer back, and write *&it to get the source link and &it to get the raw pointer.

Please note: if your type overloads operator& and returns something other than the built-in operator, your type will no longer be copied (in C ++ 03 - C ++ 0x seems to have removed it), and therefore cannot be used anymore as an elemental type in a standard container.

+5
source

It is apparently used in ATL, for example http://msdn.microsoft.com/en-us/library/5s6et3yb.aspx

+4
source

I don't know a specific example, but I could imagine a container class where you might want to return a smart pointer or an iterator. I am not saying that this necessarily makes sense.

+1
source

One good reason to overload it might be to make it private so that users cannot use it. I can’t think of any real example where you would like to prevent this, but this is apparently the most logical reason for overloading it.

+1
source

I did this once when the object had a special smart pointer. operator& silently "lifted" the selected stack the object into a heap smart version of the pointer, and this operator behaved differently as soon as the object was inside the pointer.

I no longer have the code, but there was a reason at the time. This, of course, is not a decision to take lightly, this road is lined with corpses.

+1
source

I overloaded this statement when writing classes to interact with Direct3D. It was a class of smart pointers that was supposed to return T ** from the & operator so that it could be used in functions that expect from pointer to pointer. T ** semantics are rare, but in some situations you need it.

0
source

All Articles