Why no offsetof for static struct?
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Jul 10 14:50:23 PDT 2017
On 07/10/2017 02:14 PM, FoxyBrown wrote:
> On Monday, 10 July 2017 at 20:13:46 UTC, Adam D. Ruppe wrote:
>> On Monday, 10 July 2017 at 20:01:39 UTC, FoxyBrown wrote:
>>> Cannot get the offset of static members of a struct
>>
>> That's because static members do not have an offset. They are not part
>> of the struct in memory, just in name.
>>
>>> We can clearly get a pointer to the static struct X
>>
>> There's barely any such thing as a static struct. That's just a struct
>> that stands without outside context.... which is almost all structs,
>> actually, so the term isn't special.
>>
>>> since &X.x is effectively the address of X(regardless nomenclature
>>> and terminology issues in D trying to hide this).
>>
>> No, it isn't. Static members are stored in an entirely different place
>> than non-static members. They are really just global variables in
>> memory with their in-source name being nested somewhere else.
>
>
> This is not true, just because there isn't any official statement, or
> even if denied, does not make it true. I have proof:
>
> auto GetStaticAddress(T)()
> {
> mixin("auto p = cast(T*)&T."~__traits(allMembers, T)[0]~";");
> return p;
> }
>
>
> Returns the address of a struct's static members.
Yes but that address is not offset from the beginning of any struct
object. What would be its relationship to the following two objects?
import std.stdio;
auto GetStaticAddress(T)()
{
mixin("auto p = cast(T*)&T."~__traits(allMembers, T)[0]~";");
return p;
}
struct S {
static int s;
int m;
}
void main() {
writeln("S.s is at ", GetStaticAddress!S);
auto a = S();
auto b = S();
writeln("a is at ", &a);
writeln("b is at ", &b);
}
Prints
S.s is at 7F6D68484710
a is at 7FFEADF41B68
b is at 7FFEADF41B6C
So there is no offset of S.s to speak of (i.e. number of bytes from the
beginning of) neither from a nor b.
> It's pretty obvious, the compiler seems to instantiate the static
> members simply as a sort of "singleton".
Makes sense.
> They are laid out with the same
> relative offsets as the struct(which is obvious, as that is the most
> natural way). That is all that is needed to treat the memory the static
> variables use as the struct in which they are part of. No need to make
> it any more complex than that.
S.s is sitting in memory all by itself without are relation to any other
S members.
> Just because D obfuscates that static structs have addresses, doesn't
> mean they don't.
I assume you mean "static members". Then, yes, of course they have
addresses. And you don't even need a function like GetStaticAddress():
writeln("S.s is at ", &S.s);
> No need to perpetuate a misnomer. Static structs and
> classes have addresses.
Again, I think you mean "static members of" or "instances of" structs
and classes.
Ali
More information about the Digitalmars-d-learn
mailing list