3

Here is the code snippet

#include <iostream>
struct Z
{
   Z():x(0),y(0),z(x){}
   ~Z(){}

   int x;
   int y;
   int &z; // Reference member
};
template <typename Type, typename C, typename M>
size_t Offsetof (M C::* ptr_to_member)
{
  Type type;
  return reinterpret_cast<char*> (&(type.*ptr_to_member)) - reinterpret_cast<char*> (&type);
}
int main()
{
   std::cout << Offsetof<Z>(&Z::x); // works
   std::cout << Offsetof<Z>(&Z::y); // works 
   std::cout << Offsetof<Z>(&Z::z); // doesn't work
}

We cannot create pointer to reference so the function Offsetof won't work for z.

Is there any way to take offset of a reference data member for non PODs?

Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
  • 2
    Might help : http://stackoverflow.com/questions/1129894/why-cant-you-use-offsetof-on-non-pod-strucutures-in-c – Caribou Nov 26 '12 at 10:24

1 Answers1

5

No. References are not objects, and they do not exist or have addresses or offsets. A pointer to a member reference is illegal.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • Whether a reference takes memory is unspecified. On most implementations a reference is implemented as a const pointer right? There should be some implementation specific way to do the same which I am not aware of. – Prasoon Saurav Nov 26 '12 at 10:33
  • Why? The implementation of a reference is irrelevant. – Puppy Nov 26 '12 at 10:35
  • There is no guarantee it has an offset, and even if it has an offset, it is not required to be the same for every instance of objects of this type (the compiler can use lookup tables). Sorry, that's just the way C++ is. – David Schwartz Nov 26 '12 at 10:37