Search code examples
pointerscastingaliasd

Is it safe to cast between B* and D* if D contains an object of type B as its first member?


Consider the following:

struct B { int x; }
struct D { B b; int y; }

void main() {
    auto b = cast(B*) new D();
    writeln(b.x == b.x);
    auto d = cast(D*) b;
    writeln(b.x == d.b.x);
}

Is this program guaranteed to write "true" twice? I couldn't find these rules anywhere in the D language reference.


Solution

  • Structs in D "work like they do in C", so you can have reasonable expectations on their internal layout. Be wary of hidden members of nested structs, though.

    Casting from D to B should be fine. It is not safe to cast in the other direction, because y will then refer to something after the original B variable.

    A simpler, safe way to cast from D* to B* is to take D.b's address (B* b = &d.b).