Size of a class instance at compile time

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Sun Jan 14 09:52:00 PST 2007


Daniel Keep wrote:
> Frits van Bommel wrote:
>> Frits van Bommel wrote:
>>
>>> [1]: e.g. I haven't tested using anything with explicit align(N) 
>>> declarations, not sure what happens there (would .alignof be adjusted?).
>>
>>
>> Yep, definitely breaks there. But I did find a much more elegant 
>> implementation that *does* work in that case (as well as in normal 
>> cases):
>>
>> -----
>> template InstanceSize(T)
>> {
>>     const InstanceSize =
>>         T.tupleof[$-1].offsetof + T.tupleof[$-1].sizeof;
>> }
>> ------
> 
> Just wondering; do we even need to worry about align(N) attributes? 
> AFAIK, that only applies to structures, and we can get the size of those 
> using sizeof since they're value types.

They work for classes too. Not sure if it's documented, but in my test 
file I have the following:

-----
template InstanceSize(T)
{
     const InstanceSize =
         T.tupleof[$-1].offsetof + T.tupleof[$-1].sizeof;
}

class Test {
	char c;
	int i;
}

class Test2 {
	char c;
	align(1) int i;
}

import std.stdio;

void main() {
	writefln("Test:");
	writefln("Static size: ", InstanceSize!(Test));
	writefln("Actual size: ", Test.classinfo.init.length);
	writefln();
	writefln("Test2:");
	writefln("Static size: ", InstanceSize!(Test2));
	writefln("Actual size: ", Test2.classinfo.init.length);
}
-----

Which gives size 16 and 13 for Test and Test2, respectively.

So alignment declarations definitely makes a difference even for classes.

> http://digitalmars.com/d/attribute.html#align -- says down the bottom of 
> that heading that it only applies to structs and struct members.

Then I guess either the spec or the implementation is wrong.

> I just knocked up a slightly more robust version that should 
> *theoretically* still work even if the members are moved around.  It 
> basically just does the same thing yours does, but it runs over the 
> whole tuple, and passes out the largest value it finds.

Ah, that's a good solution to that problem I guess.
Unless there's ever any weird need to put overhead bytes at the end that 
should work.
(Where are interface vtable pointers put? [tests] Damn, looks like 
they're at the end :( )

> Obviously, it doesn't help for the above two points, but Walter seems to 
> like stuff at the start of the block, not trailing off the end.  Plus, 
> when would a class require padding?

Apparently, implementing an interface counts as well...


More information about the Digitalmars-d-learn mailing list