c++ - 在 C++ 中使用 std::addressof() 函数模板而不是使用 operator& 有什么好处吗?

标签 c++

如果addressof operator& 运行良好,那么为什么C++ 引入了addressof() 函数? & 运算符从一开始就是 C++ 的一部分 - 为什么要引入这个新函数?它比 C 的 & 运算符有什么优势吗?

最佳答案

一元 operator& 可能会为类类型重载,从而为您提供除对象地址之外的其他内容,而 std::addressof() 将始终为您提供其实际地址.
Contrived example :

#include <memory>
#include <iostream>

struct A {
    A* operator &() {return nullptr;}
};

int main () {
    A a;
    std::cout << &a << '\n';              // Prints 0
    std::cout << std::addressof(a);       // Prints a's actual address
}

如果您想知道这样做何时有用:
What legitimate reasons exist to overload the unary operator&?

关于c++ - 在 C++ 中使用 std::addressof() 函数模板而不是使用 operator& 有什么好处吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32680208/

相关文章:

c++ - 从文本文件中排序数据

c++ - 如何正确判断文本文件的字符编码?

c++ - 验证并验证 NoMoreInteractions 到 gtest

c++ - VS2015 在 C++ 中链接 .dll/.so

c++ - 如何使用 CMake 获得包含所有项目的 VS 解决方案和单个项目的解决方案

c++ - 函数参数究竟何时被破坏?

使用和不使用命名空间标准的 C++ 长 double 差异;

c++ - 正则表达式捕获使代码崩溃

C++继承问题错误C2084函数已经有一个主体

c++ - 将一维数组转换为二维 vector C++