打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
More C++ Idioms/Address Of
More C++ Idioms/Address Of
Intent
Find address of an object of a class that has an overloaded unary ampersand (&) operator.
发现一个重载了一元(&)操作符类的对象的地址
Motivation
C++ allows overloading of unary ampersand (&) operator for class types. The return type of such an operator need not be the actual address of the object. Intentions of such a class are highly debatable but the language allows it nevertheless. Address-of idiom is way to find the real address of an object irrespective of the overloaded unary ampersand operator and its access protection.
C++允许类类型重载一元(&取地址)操作符。这样的一个操作符返回的类型可能不是对象真实的地址。这样一个的类是具有高度争议的,但是语言允许这样做。Address-of是发现对象真实的地址的方法,不考虑一元(&)运算符的重载和它的访问限制。
In the example below, main function fails to compile because operator & of nonaddressable class is private. Even if it were accessible, a conversion from its return type double to a pointer would not have been possible or meaningful.
在下面的例子中,主函数是编译失败的因为nonaddressable的&运算符是private的,即使它是可以访问的,从它的返回类型double转换成一个指针也将是没有意义的。
class nonaddressable 
{
public:
    typedef double useless_type;
private:
    useless_type operator&() const;
};

int main()
{
  nonaddressable na;
  nonaddressable * naptr = &na; // Compiler error here.
}
Solution and Sample Code
The Address-of idiom retrieves the address of an object using a series of casts.
Address-of重新获取对象的地址通过使用一系列的强制转换。
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.
}
Known Uses
This function is already in the <memory> header of the new C++ standard C++11.
在新的C++11中这个函数已经存在在memory头文件中了

资料
关于addressof实现原理的解析http://blog.csdn.net/demon__hunter/article/details/5450498

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
C++操作符重载(“关系操作符”)
编程术语英语翻译(一)
c++中重载输出操作符,为什么要返回引用
SQL NULL 值
<STL源码剖析>阅读笔记之 仿函数和适配器
Function Objects (STL)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服