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?
Asked
Active
Viewed 4,962 times
90

jww
- 97,681
- 90
- 411
- 885

Destructor
- 14,123
- 11
- 61
- 126
-
1It looks very close to a duplicate to me but I don't feel strong enough to dup hammer it myself but it is relevant regardless. It would be more convincing if you explained why you felt it was different. – Shafik Yaghmour Sep 24 '15 at 19:33
-
5One would be hard-pressed to find a page discussing `std::addressof` without mentioning its ability to bypass overloaded unary `operator&`. This question shows zero research effort. – T.C. Sep 25 '15 at 06:51
-
1@T.C.: If this question shows 0 research effort then it would not be possible to get so much upvotes for it. – Destructor Sep 25 '15 at 07:55
1 Answers
141
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&?

Community
- 1
- 1

Baum mit Augen
- 49,044
- 25
- 144
- 182