What's the best way to get address difference between a class variable and the starting address of a class object?

256 views Asked by At

Need to generate unique keys for the class data members. Hence I am thinking of getting the difference between the address of the variable minus the address of the class object. For example:

struct X {
  int i;  // &i - &X() = 0  (GCC)
  double d;  // &d - &X() = 8  (GCC)
};

This is a one time exercise and hence will be happening in very beginning of the code execution for all the interested classes. So typically I will be declaring a dummy object of the class and finding the address difference by typecasting. Such as:

X x;
keyOf_i = long(&x.i) - long(&x);
keyOf_d = long(&x.d) - long(&x);

Is there any better way?
Assume that the access specifier (private) are not the problem.

Will be also interested, if someone has got any other approach to generate unique keys for class data variables apart from this way.


Update: With using offseof() macro, I am getting following warning in G++-6:

offsetof within non-standard-layout type ‘MyClass’ is undefined

Actually I have some string & other class variables as well inside MyClass. I am fine, even if this undefined thing gives unique address whatsoever. However, would like to get more information of offsetof() and other alternatives.

1

There are 1 answers

0
A.N On BEST ANSWER

How about using offsetof() macro for this. Check http://man7.org/linux/man-pages/man3/offsetof.3.html for more details.

Sample code below from the man page:

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    struct s {
        int i;
        char c;
        double d;
        char a[];
    };

    /* Output is compiler dependent */

    printf("offsets: i=%ld; c=%ld; d=%ld a=%ld\n",
            (long) offsetof(struct s, i),
            (long) offsetof(struct s, c),
            (long) offsetof(struct s, d),
            (long) offsetof(struct s, a));
    printf("sizeof(struct s)=%ld\n", (long) sizeof(struct s));

    exit(EXIT_SUCCESS);
}