Last modified on 10 January 2014, at 15:34

More C++ Idioms/Address Of

Address OfEdit

IntentEdit

Find address of an object of a class that has an overloaded unary ampersand (&) operator.

Also Known AsEdit

MotivationEdit

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.

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.

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 CodeEdit

The Address-of idiom retrieves the address of an object using a series of casts.

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 UsesEdit

This function is already in the <memory> header of the new C++ standard C++11.

Related IdiomsEdit

ReferencesEdit