std::addressof
来自cppreference.com
在标头 <memory> 定义 | ||
template<class T > T* addressof( T& arg )noexcept; | (1) | (C++11 起) (C++17 起为 constexpr ) |
template<class T > const T* addressof(const T&&)= delete; | (2) | (C++11 起) |
1) 获得对象或函数 arg 的实际地址,即使存在
operator&
的重载也是如此。2) 右值重载被弃置,以避免取 const 右值的地址。
若 | (C++17 起) |
| (C++23 起) |
目录 |
[编辑]参数
arg | - | 对象或函数左值 |
[编辑]返回值
指向 arg 的指针。
[编辑]可能的实现
以下实现不是 constexpr,因为 reinterpret_cast 不能用于常量表达式。需要编译器支持(见后述)。
template<class T>typenamestd::enable_if<std::is_object<T>::value, T*>::type addressof(T& arg)noexcept{returnreinterpret_cast<T*>(&const_cast<char&>(reinterpret_cast<constvolatilechar&>(arg)));} template<class T>typenamestd::enable_if<!std::is_object<T>::value, T*>::type addressof(T& arg)noexcept{return&arg;} |
此函数的正确实现要求编译器支持:GNU libstdc++、LLVM libc++、Microsoft STL。
[编辑]注解
功能特性测试宏 | 值 | 标准 | 功能特性 |
---|---|---|---|
__cpp_lib_addressof_constexpr | 201603L | (C++17) | constexprstd::addressof |
addressof
的 constexpr 是由 LWG2296 添加的,而 MSVC STL 将该更改作为缺陷报告应用到 C++14 模式。
在一些怪异的情况下,实参依赖查找导致使用内建 operator& 为非良构,即使它未被重载,而 std::addressof
能用作替代。
template<class T>struct holder { T t;}; struct incomp; int main(){ holder<holder<incomp>*> x{};// &x; // 错误:实参依赖查找试图实例化 holder<incomp> std::addressof(x);// OK}
[编辑]示例
可以为指针封装器类重载 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 <<'\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);// 调用 int** 重载 f(std::addressof(p));// 调用 Ptr<int>* 重载,(= this)}
可能的输出:
Ctor this = 0x7fff59ae6e88 int** overload called with p = 0x7fff59ae6e90 Ptr overload called with p = 0x7fff59ae6e88
[编辑]缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
---|---|---|---|
LWG 2598 | C++11 | std::addressof<const T> 能取右值的地址 | 由被删除的重载禁止 |
[编辑]参阅
默认的分配器 (类模板) | |
[静态] | 获得指向其实参的可解引用指针 ( std::pointer_traits<Ptr> 的公开静态成员函数) |