定义于头文件
<memory>
|
||
(1) | ||
template< class T >
T* addressof(T& arg) noexcept; |
(C++11 起) (C++17 前) |
|
template< class T >
constexpr T* addressof(T& arg) noexcept; |
(C++17 起) | |
template <class T>
const T* addressof(const T&&) = delete; |
(2) | (C++17 起) |
arg
的实际地址,即使存在 operator&
的重载
表达式 |
(C++17 起) |
目录 |
arg | - | 左值对象或函数 |
指向 arg
的指针。
template< class T > T* addressof(T& arg) { return reinterpret_cast<T*>( &const_cast<char&>( reinterpret_cast<const volatile char&>(arg))); } |
注意:上述实现被过分简化且不是 constexpr
(这要求编译器支持)。
operator& 可以为指针封装器类重载,以获得指向指针的指针:
#include <iostream> #include <memory> template<class T> struct Ptr { T* pad; // 增加填充以显示‘ this ’和‘ data ’的区别 T* data; Ptr(T* arg) : pad(nullptr), data(arg) { std::cout << "Ctor this = " << this << std::endl; } ~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); // 调用 int** 重载 f(std::addressof(p)); // 调用 Ptr<int>* 重载,( = this ) }
可能的输出:
Ctor this = 0x7fff59ae6e88 int** overload called with p = 0x7fff59ae6e90 Ptr overload called with p = 0x7fff59ae6e88
默认的分配器 (类模板) |
|
[静态]
|
获得指向其参数的可解引用指针 ( std::pointer_traits 的公开静态成员函数)
|