2

Say we have an object a like this:

struct B {
  void access_a() {
    A* a = reinterpret_cast<A*>(reinterpret_cast<char*>(this)
                                - offsetof(A, b));
    // is accessing a here well defined, assuming this object
    // is one that is inside struct A?
  }
};
struct A {
  /* one or more standard layout types before b */
  B b;
} a;

a.b.access_a();

Theoretically we have indeed a pointer that points to an instance of A, and at least under certain circumstances this kind of (ugly) code seems to do what's intended. Is it well defined though? Can the compiler assume that accessing one member of an object won't alter the others (if the accessed object itself contains no pointers to the parent), or do all the child objects belong in some sort of shared mutable group?

user
  • 934
  • 6
  • 17
M. M.
  • 21
  • 2
  • What do you mean by *accessing one member of an object won't alter the others*? Do you mean alter the member addresses? Or do you want to know if the compiler will assume the values contained in the other members won't change? How is that relevant to the first question? I'm trying understand the question regarding a potential *mutable group*. – wally Mar 05 '17 at 17:36
  • Possible duplicate: http://stackoverflow.com/questions/1453393/legit-uses-of-the-offsetof-macro-in-c-c – πάντα ῥεῖ Mar 05 '17 at 17:44
  • Valid question, but just in case you want to use that in actual code: This *strongly* smells like broken class design. – Baum mit Augen Mar 05 '17 at 17:58

1 Answers1

0

One possible problem lies with the usage of the offsetof macro, which can only be used with POD types.

(Wiki:)

A Plain Old Data Structure in C++ is an aggregate class that contains only PODS as members, has no user-defined destructor, no user-defined copy assignment operator, and no nonstatic members of pointer-to-member type.

So as long as your struct A is defined to comply with the rules above, it is guaranteed to work (but indeed as stated it is bad practice and ugly code). But if it's not, you have undefined behaviour.

Steeve
  • 1,323
  • 1
  • 12
  • 23