重载一元运算符 & 是否有意义? [英] Does it ever make sense to overload unary operator &?
问题描述
因此,C++ 允许重载一元 operator &
(address).当 operator &
正确重载时,您是否知道任何现实世界 示例?第二个更具体的问题是,您是否知道 operator &
在保留地址语义的同时正确重载的任何现实世界示例?TIA
So, C++ allows overloading the unary operator &
(address). Are you aware of any real-world example when operator &
was rightfully overloaded? And a second, more specific question, are you aware of any real-world example when operator &
was rightfully overloaded while preserving address semantics? TIA
推荐答案
我有 207 个 真实世界 operator &()
示例:代码搜索 1, 代码搜索 2.
I've got 207 real-world examples of operator &()
: Code search 1, Code search 2.
包括SafeInt<>
(获取底层裸整数),boost::gil(显然也是为了让步原始数据),Mozilla(说定义操作符是有风险的,但是,嘿,我们知道我们在做什么."),wxWidgets,Armagtron 等等.
Including SafeInt<>
(to get the underlying naked integer), boost::gil (apparently also to yield the raw data), Mozilla (that say "it is risky to define operator&, but, hey, we know what we're doing."), wxWidgets, Armagetron and lots of more.
似乎有些人使用迭代器习语 &*it
来获取原始引用或向后的指针,并编写 *&it
来获取原始引用和 &it
获取原始指针.
It seems some use the iterator idiom &*it
to get a raw reference or pointer backwards, and write *&it
to get a raw reference and &it
to get a raw pointer.
请注意,一旦您的类型重载 operator&
并返回与内置运算符不同的内容,您的类型就不再是 CopyConstructible(在 C++03 中 - C++0x 似乎已经解除it),因此不能再用作标准容器中的元素类型.
Notice that once your type overloads operator&
and returns something different than the built-in operator, your type is not CopyConstructible anymore (in C++03 - C++0x seems to have lifted it), and so cannot be used as element-type in a Standard container anymore.
这篇关于重载一元运算符 & 是否有意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!