如果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/