0

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.

iammilind
  • 68,093
  • 33
  • 169
  • 336
  • @iammilind I can't think about difference answer, `offsetof` is undefined behavior for non standard layout – Danh Dec 19 '16 at 12:03
  • @SamVarshavchik, Danh can you elaborate more on the "standard layout types". In what kind of situations this difference can fail? I thought that, the difference between the address of the class object and the address of its data member, always remain constant. When will this difference become undefined? BTW, I am not interested in the accurate difference as such. Rather, I am just interested in unique difference for all the variables of the class. Please suggest. – iammilind Dec 19 '16 at 12:07
  • Google for "pointer-to-member". A pointer-to-member is a thing that lets you access some member of a struct or class instance if you are given a pointer to the instance as well. – gnasher729 Dec 19 '16 at 12:09
  • You might want to use uintptr_t to make sure the pointers fit in the integers. – stefaanv Dec 19 '16 at 12:46

1 Answers1

1

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);
}
A.N
  • 541
  • 2
  • 13