Is there any advantage of using std::addressof() function template instead of using operator& in C++?
C++C++ Problem Overview
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?
C++ Solutions
Solution 1 - C++
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:
https://stackoverflow.com/questions/6495977/what-legitimate-reasons-exist-to-overload-the-unary-operator