I have got a class that has overloaded unary operator&
. The objects of that type were created using new
, so address of variable was accessible but now I need to use static object. Is it possible to get its address?
Asked
Active
Viewed 9,034 times
24

Ashot
- 10,807
- 14
- 66
- 117
-
1Is the *unary* `operator&` in fact overloaded? – Fred Larson Oct 30 '14 at 13:55
-
@FredLarson I was surprised too look at: http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Member_and_pointer_operators – KugBuBu Oct 30 '14 at 13:55
-
@KugBuBu: Yes, I saw that it can be overloaded. But the question is not explicit on which actually is overloaded in this case. I've seen classes overload binary `operator&` (say, for string concatenation). It's unusual to overload the unary operator. – Fred Larson Oct 30 '14 at 13:57
-
2@FredLarson: The question would be rather trivial if it weren't about the unary operator. – Mike Seymour Oct 30 '14 at 14:01
-
@MikeSeymour: Exactly why it's important information. – Fred Larson Oct 30 '14 at 14:24
-
1Essentially the same question http://stackoverflow.com/q/1142607/57428 – sharptooth Oct 30 '14 at 15:32
-
@MikeSeymour Nvm, I was being silly. This is why staying up for more than 20 hours is never a good idea. – Pharap Oct 31 '14 at 14:18
2 Answers
36
In C++11 or later, std::addressof(object)
, declared by the <memory>
header.
Historically, it was more grotesque, especially if you wanted to deal with const
and volatile
qualifiers correctly. One possibility used by Boost's implementation of addressof
is
reinterpret_cast<T*>(
&const_cast<char&>(
reinterpret_cast<const volatile char &>(object)))
first adding qualifers while converting to char&
so that reinterpret_cast
would work however object
were qualified; then removing them so that the final conversion would work; then finally taking the address and converting that to the correct type. As long as T
has the same qualifiers as object
(which it will as a template parameter deduced from object
), the resulting pointer will be correctly qualified.

Mike Seymour
- 249,747
- 28
- 448
- 644
31
Since C++11, you may use the function std::addressof

Jonathan Wakely
- 166,810
- 27
- 341
- 521

Jarod42
- 203,559
- 14
- 181
- 302