std::addressof

Header: <memory>

  1. Obtains the actual address of the object or function arg, even in presence of overloaded operator&.

# Declarations

template< class T >
T* addressof( T& arg ) noexcept;

(since C++11) (constexpr since C++17)

template< class T >
const T* addressof( const T&& ) = delete;

(since C++11)

# Parameters

# Return value

Pointer to arg.

# Notes

constexpr for addressof is added by LWG2296, and MSVC STL applies the change to C++14 mode as a defect report.

There are some weird cases where use of built-in operator& is ill-formed due to argument-dependent lookup even if it is not overloaded, and std::addressof can be used instead.

# Example

#include <iostream>
#include <memory>
 
template<class T>
struct Ptr
{
    T* pad; // add pad to show difference between 'this' and 'data'
    T* data;
    Ptr(T* arg) : pad(nullptr), data(arg)
    {
        std::cout << "Ctor this = " << this << '\n';
    }
 
    ~Ptr() { delete data; }
    T** operator&() { return &data; }
};
 
template<class T>
void f(Ptr<T>* p)
{
    std::cout << "Ptr   overload called with p = " << p << '\n';
}
 
void f(int** p)
{
    std::cout << "int** overload called with p = " << p << '\n';
}
 
int main()
{
    Ptr<int> p(new int(42));
    f(&p);                // calls int** overload
    f(std::addressof(p)); // calls Ptr<int>* overload, (= this)
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 2598C++11std::addressof could take address of rvaluesdisallowed by a deleted overload

# See also