Is it possible to manually calculate the byte offset of a class member?

That is, what standard is used by the compiler to create the class? For example, suppose I have a class Cwith members x, yand z, and I want to know the offset zinside this class. Can I just add the data sizes of other members, for example, for a structure?

+5
source share
7 answers

No. You can not.
Compilers are free to align the elements as they wish. This is a compiler implementation detail.

If you work with POD , you can use offsetof .

Non-POD, , .

+8

, , . , .

offset = (unsigned char*)&(this->z) - (unsigned char*)this;

#include <iostream>

class C
{
public:
    int x;
    char y;
    int z;
    size_t offset() const
    {
        return (unsigned char*)&(this->z) - (unsigned char*)this;
    }
};

int main()
{
    C c;
    std::cerr << "Offset(cast): " << c.offset() << "\n";
}
+4

, , . (. @bert-jan @sodved ).

! ++ , .

, , !

? - . .


: offsetof -POD- ++? .

+2

&(class_name::member_name) .

+1

. , .

Microsoft :

#pragma pack(push,1)
struct Foo {
  uint8 a;
  uint32 b;
};
#pragma pack(pop)

I can convey (rumored only) that GCC also supports this with the extension.

0
source
    #define _OFFSET(p_type, p_member) (size_t)(&((p_type *)NULL)->p_member)

    struct a
   {
       int a, b;
   };

   cout << _OFFSET(struct a, b); // output is your offset
-1
source

All Articles