Is there any advantage of using std::addressof() function template instead of using operator& in C++? [duplicate]

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?


Solution 1:

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&?