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头文件中了