命名空间
变体
操作

std::addressof

来自 cppreference.cn
< cpp‎ | memory
 
 
内存管理库
(仅用于说明*)
未初始化内存算法
(C++17)
(C++17)
(C++17)
受约束的未初始化
内存算法
C 库

分配器
内存资源
垃圾回收支持
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
未初始化存储
(直到 C++20*)
(直到 C++20*)
显式生命周期管理
 
在头文件 <memory> 中定义
template< class T >
T* addressof( T& arg ) noexcept;
(1) (自 C++11 起)
(constexpr 自 C++17 起)
template< class T >
const T* addressof( const T&& ) = delete;
(2) (自 C++11 起)
1) 获取对象或函数 arg 的实际地址,即使存在重载的 operator&
2) 删除右值重载以防止获取 const 右值的地址。

表达式 std::addressof(e) 是一个常量子表达式,如果 e 是一个左值常量子表达式。

(自 C++17 起)

目录

[编辑] 参数

arg - 左值对象或函数

[编辑] 返回值

指向 arg 的指针。

[编辑] 可能的实现

下面的实现不是 constexpr,因为 reinterpret_cast 在常量表达式中不可用。 需要编译器支持(见下文)。

template<class T>
typename std::enable_if<std::is_object<T>::value, T*>::type addressof(T& arg) noexcept
{
    return reinterpret_cast<T*>(
               &const_cast<char&>(
                   reinterpret_cast<const volatile char&>(arg)));
}
 
template<class T>
typename std::enable_if<!std::is_object<T>::value, T*>::type addressof(T& arg) noexcept
{
    return &arg;
}

此函数的正确实现需要编译器支持:GNU libstdc++LLVM libc++Microsoft STL

[编辑] 注解

特性测试 Std 特性
__cpp_lib_addressof_constexpr 201603L (C++17) constexpr std::addressof

addressofconstexprLWG2296 添加,并且 MSVC STL 将此更改应用于 C++14 模式作为缺陷报告。

在某些奇怪的情况下,由于实参依赖查找,即使未重载,使用内置的 operator& 也是非良构的,并且可以使用 std::addressof 代替。

template<class T>
struct holder { T t; };
 
struct incomp;
 
int main()
{
    holder<holder<incomp>*> x{};
    // &x; // error: argument-dependent lookup attempts to instantiate holder<incomp>
    std::addressof(x); // OK
}

[编辑] 示例

operator& 可以为指针包装器类重载,以获取指向指针的指针

#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)
}

可能的输出

Ctor this = 0x7fff59ae6e88
int** overload called with p = 0x7fff59ae6e90
Ptr   overload called with p = 0x7fff59ae6e88

[编辑] 缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

DR 应用于 发布时的行为 正确的行为
LWG 2598 C++11 std::addressof<const T> 可以获取右值的地址 被删除的重载禁用

[编辑] 参见

默认分配器
(类模板) [编辑]
[静态]
获取指向其参数的可解引用指针
(std::pointer_traits<Ptr> 的公共静态成员函数) [编辑]