使用std :: addressof()函数模板而不使用operator&在C ++中? [英] Is there any advantage of using std::addressof() function template instead of using operator& in C++?
问题描述
如果 addressof operator&
运行良好,那么为什么C ++引入了 addressof()
功能? &
运算符从一开始就是C ++的一部分-那么为什么要引入这个新函数?与C的&
运算符相比,它提供任何优势吗?
If addressof operator&
works well then why C++ has introduced addressof()
function? The &
operator is part of C++ from the beginning - why this new function is introduced then? Does it offer any advantages over C's &
operator?
推荐答案
一元 operator&
可能会因类类型的重载而为您提供除对象地址以外的其他内容,而 std :: addressof()
将始终为您提供其实际地址。 :
The unary operator&
might be overloaded for class types to give you something other than the object's address, while std::addressof()
will always give you its actual address.
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
}
如果您想知道这样做何时有用:< br>
存在哪些合理的原因使一元代码过载运算符& ;?
If you wonder when doing this is useful:
What legitimate reasons exist to overload the unary operator&?
这篇关于使用std :: addressof()函数模板而不使用operator&在C ++中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!