[Issue 12714] New: .offsetof problems in structs with alias this

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Thu May 8 00:52:06 PDT 2014


https://issues.dlang.org/show_bug.cgi?id=12714

          Issue ID: 12714
           Summary: .offsetof problems in structs with alias this
           Product: D
           Version: D2
          Hardware: x86
                OS: Windows
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: DMD
          Assignee: nobody at puremagic.com
          Reporter: bearophile_hugs at eml.cc

This issue is currently an enhancement request, but I think it's borderline a
bug.

This documentation page:
http://dlang.org/struct.html

Gives a definition of the .offsetof field:

.offsetof   Offset in bytes of field from beginning of struct

But in presence of structs with "alias this" .offsetof has problems:

A comment from Artur Skawina:

>if the object does not contain the requested member, but implicitly converts to another one that does have such field then the expression compiles, but yields a bogus value.<


Example code:


struct Foo {
    int f1, f2;
}
struct Bar {
    int b1, b2, b3, b4;
    Foo x;
    alias x this;
}
void main() {
    Bar b;
    assert(cast(void*)&b.f2 - cast(void*)&b == 20);
    static assert(Bar.x.offsetof == 16);
    static assert(Bar.f2.offsetof == 4); // ***
}


I think this is a little trap for D programmers.
I expect "Bar.f2.offsetof" to return 20 (or not to compile).


In a struct without "alias this" this situation is more clear:

struct Foo {
    int f1, f2;
}
struct Bar {
    int b1, b2, b3, b4;
    Foo x;
}
void main() {
    Bar b;
    assert(cast(void*)&b.x.f2 - cast(void*)&b == 20);
    static assert(Bar.x.offsetof == 16);
    static assert(Bar.x.f2.offsetof == 4);
}


Now "Bar.f2.offsetof" doesn't compile, and "Bar.x.f2.offsetof" is 4 because
it's the offset of the field f2 relative to the start of the struct instance x.

--


More information about the Digitalmars-d-bugs mailing list