更多 C++ 习语/地址运算符
外观
地址运算符
[编辑 | 编辑源代码]意图
[编辑 | 编辑源代码]查找具有重载的一元取地址运算符 (&) 运算符的类的对象的地址。
也称为
[编辑 | 编辑源代码]此习语没有已知的别名。
动机
[编辑 | 编辑源代码]C++ 允许为类类型重载一元取地址运算符 (&)。此类运算符的返回值类型不必是对象的实际地址。此类类的意图存在争议,但语言允许它。地址运算符是一种在不考虑重载的一元取地址运算符及其访问保护的情况下找到对象真实地址的方法。
在下面的示例中,main
函数无法编译,因为类 nonaddressable
的 operator &
是私有的。即使它可以访问,从它的返回值类型 double
到指针的转换也不可能或没有意义。
class nonaddressable
{
public:
typedef double useless_type;
private:
useless_type operator&() const;
};
int main()
{
nonaddressable na;
nonaddressable * naptr = &na; // Error: operator & of type nonadressable is private.
}
解决方案和示例代码
[编辑 | 编辑源代码]地址运算符使用一系列强制转换来检索对象的地址。
template <class T>
T * addressof(T & v)
{
return reinterpret_cast<T *>(& const_cast<char&>(reinterpret_cast<const volatile char &>(v)));
}
int main()
{
nonaddressable na;
nonaddressable * naptr = addressof(na); // No more compiler error.
}
C++11
[编辑 | 编辑源代码]在 C++11 中,模板 std::addressof
[1](在 <memory>
头文件中)被添加来解决这个问题。从 C++17 开始,该模板也被标记为 constexpr
。