在 C + + 中使用 std: : addressof()函数模板而不使用操作符 & 有什么好处吗?

如果 地址 operator&工作得很好,那么为什么 C + + 引入了 addressof()函数?&操作符从一开始就是 C + + 的一部分——那么为什么要引入这个新函数呢?它比 C 的 &操作员有什么优势吗?

4817 次浏览

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
}

If you wonder when doing this is useful:
What legitimate reasons exist to overload the unary operator&?