Is there any advantage to using the std :: addressof () function template instead of using the & (address of) operator in C ++?

If the address & operator works well, why did C ++ introduce the addressof() function? The & operator is part of C ++ from the very beginning - why was this new feature introduced then? Does it have any advantages over the C & operator?

+75
c ++
Sep 20 '15 at 13:58
source share
1 answer

The unary operator& can be overloaded for class types to give you something other than the address of an object, while std::addressof() will always indicate your actual address.
Thoughtful 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 actual address } 

If you are wondering when this is useful:
What are the legitimate reasons for reinstalling the unary operator &?

+115
Sep 20 '15 at 14:00
source share



All Articles