24

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?

Ashot
  • 10,807
  • 14
  • 66
  • 117

2 Answers2

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