size of a class instance

Bill Baxter wbaxter at gmail.com
Thu Nov 16 10:42:32 PST 2006


Lionello Lunesu wrote:
> Bill Baxter wrote:
>> I guess when it comes down to it, finding the size of a class is 
>> really only useful for satisfying one's curiosity and optimizing 
>> member orders to get better alignment.  And for that purpose I guess 
>> it doesn't really have to be that intuitive a name.

> Lionello Lunesu wrote:
>
> Uh, according to the D spec, the order of the members of a _class_ may 
> be changed by the compiler, so optimizing manually would have no effect.
> 
> L.

Tell that to dmd 0.174:

import std.stdio : writefln;

class A
{
     char a;
     int  b;
     char c;
     char d;
     char e;
}
class B
{
     char a;
     char c;
     char d;
     char e;
     int  b;
}

void main()
{
     writefln("Sizeof A = ", A.classinfo.init.length);
     writefln("Sizeof B = ", B.classinfo.init.length);
}

 >> Sizeof A = 19
 >> Sizeof B = 16

And in practice A will probably take 20 bytes, because the thing after 
it in memory will want to be aligned on a 4-byte boundary too.

So the key word in the spec is that the order _may_ be changed, not that 
it will.  C and C++ specs have always had the same sort of language, but 
in practice very few if any compilers reorder members.  They will, 
however, add in padding to get optimal alignment.

Yes, optimizations such as the above are, strictly speaking, 
implementation-dependent.  But that's OK if you've fixed your 
implementation.

--bb



More information about the Digitalmars-d-learn mailing list