5

_com_ptr_ has an overloaded operator&() with a side effect. If I have a variable:

_com_ptr_t<Interface> variable;

How could I retrieve its address (_com_ptr_t<Interface>* pointer) without calling the overloaded operator and triggering the side effect?

sharptooth
  • 167,383
  • 100
  • 513
  • 979

3 Answers3

7

I've seen this case pop up in an ISO meeting as it broke some offsetof() macro implementations (LWG 273). The solution: &reinterpret_cast<unsigned char&>(variable)

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • Could this ever bite me in some surprising case? – sharptooth Jul 17 '09 at 11:11
  • use boost::address_of. It is based on implementation provided in this post. I think it will a part of the upcoming standard. – ovanes Jul 17 '09 at 11:38
  • @sharptooth: Probably not. This solution has quite reasonable behavior. Taking the address of an unsigned char lvalue is perfectly well defined, and reinterpret_cast to unsigned char& should work even if the casted object defines `operator unsigned char` itself. – MSalters Jul 17 '09 at 13:29
3

I define this utility function:

template<typename T>
T *GetRealAddr(T &t)
    { return reinterpret_cast<T*>(&reinterpret_cast<unsigned char &>(t)); }
Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284
0

&variable.GetInterfacePtr();

Goz
  • 61,365
  • 24
  • 124
  • 204
  • 1
    This retrieves the address of the pointer stored in the smart pointer. However, I think question is about how to get the address of the smart pointer. – Martin Liversage Jul 17 '09 at 11:12