简体   繁体   中英

C++ offset of member variables?

I have:

class Foo {
  int a;
  int b;
  std::string s;
  char d;
};

Now, I want to know the offset of a, b, s, d given a Foo*

Ie suppose I have:

Foo *foo = new Foo();
(char*) foo->b == (char*) foo + ?? ; // what expression should I put in ?

I don't know exactly why you want the offset of a member to your struct , but an offset is something that allows to to get a pointer to a member given the address of a struct. (Note that the standard offsetof macro only works with POD-structs (which yours is not) so is not a suitable answer here.)

If this is what you want to do, I would suggest using a pointer-to-member as this is a more portable technique. eg

int main()
{
    int Foo::* pm = &Foo::b;

    // Pointer to Foo somewhere else in the program
    extern Foo* f;

    int* p = &(f->*pm);
}

Note that this will only work if b isn't private in Foo , or alternative you could form the pointer to member in a member function or friend of Foo .

You should take into account that the offset inside structs are compiler-dependent. Different compilers can put padding zeroes or not not only at the end of the struct, but even in the middle of the struct (though I recognize this is more rare). Ie, the result of messing directly with offsets instead of accessing the members in the "standard way" is undefined behaviour.

The solution given by Charles Balley is the more sensible one. Anyway, I don't quite understand what is your ultimate goal with your question. Specifically,

Foo *foo = new Foo();
(char*) foo->b == (char*) foo + ?? ;

Does not makes sense to me at all. Do you want to assign to foo->b its own offset inside Foo?

Maybe what you are trying to do is to use b inside foo as a char*, in that case the question would be:

Foo *foo = new Foo();
char* ptr == (char*) foo + ?? ;

Maybe you sometimes want to treat b as an int, and sometimes as a char *, in that case, you could try to do the following change (assuming that you simply forgot to put public):

class Foo {
public:
    int a;
    union b {
        int intB;
        char * chrB;
    }
    int c;
    // ...
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM