Comment #0 by bearophile_hugs — 2014-05-08T07:52:06Z
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.
Comment #1 by robert.schadek — 2024-12-13T18:20:27Z