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?
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&?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With