D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 12714 - .offsetof problems in structs with alias this
Summary: .offsetof problems in structs with alias this
Status: NEW
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: x86 Windows
: P4 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2014-05-08 07:52 UTC by bearophile_hugs
Modified: 2024-12-13 18:20 UTC (History)
0 users

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description bearophile_hugs 2014-05-08 07:52:06 UTC
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 dlangBugzillaToGithub 2024-12-13 18:20:27 UTC
THIS ISSUE HAS BEEN MOVED TO GITHUB

https://github.com/dlang/dmd/issues/17657

DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB