Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 763
Destructor Avatar asked Sep 20 '15 13:09

Destructor


Video Answer


1 Answers

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

like image 99
Baum mit Augen Avatar answered Sep 18 '22 23:09

Baum mit Augen