Jeremie Pelletier Wrote: > Justin Johansson wrote: > > Jarrett Billingsley Wrote: > > > >> On Sat, Oct 3, 2009 at 5:50 PM, Justin Johansson <n...@spam.com> wrote: > >>> How does one determine the sizeof (in bytes) of an instance of a class in > >>> D? > >>> > >>> .sizeof works as advertised for structs, but for reference types, > >>> .sizeof yields the sizeof the referencing variable (effectively same as > >>> size of a pointer) > >>> and not the size of the underlying instance. > >>> > >>> I did try scanning the NG and read spec_D1.00.pdf. Perhaps I missed it > >>> in the latter. > >>> > >>> btw. I was poking under the hood of std.xml and though, wow, instances of > >>> Element > >>> class look humongous, and so I'm interested to how exactly how humongous. > > > >> There's no way to get it at compile-time in D1. The best you can do is > >> Class.classinfo.init.length. > >> > >> In D2, you can use __traits(classInstanceSize, Class). > > > > > > Thanks Jeremie and Jarrett for answers. > > > > For investigative purposes (rather than adding up class member sizes in my > > head), > > would I get a fair answer if I copied the class data members into a struct, > > did a struct > > sizeof and added 4 bytes to allow for a virtual function table pointer (in > > the class and > > assuming the class has a VFT)? > > You forgot the monitor pointer of the class, so thats (size_t.sizeof * > 2) to add to the size of the struct. > > I wasn't aware of the traits method either, I just made this helper > template to simplify its syntax: > > template SizeOf(alias C) if(is(C == class)) { > enum ClassSizeof = __traits(classInstanceSize, C); > }
Okay so PODO alone is 8 bytes. writefln( "Object: %d", Object.classinfo.init.length); Object: 8 And we're talking 9 bytes for a simple boxed bool and 12 bytes for a simple boxed 32-bit integer by the looks of things. class Foo { bool value; } class Bar { int value; } writefln( "Foo: %d", Foo.classinfo.init.length); writefln( "Bar: %d", Bar.classinfo.init.length); Foo: 9 Bar: 12 On top of that there is possibly alignment in the heap so my 9 byte Foo would occupy 12 or 16 bytes of address space. Would that be correct? Thanks for answers. Justin.