Thread overview
Finding the allocated size of a class?
Nov 10, 2007
Christopher Wright
Nov 10, 2007
Christopher Wright
Nov 11, 2007
Christian Kamm
November 10, 2007
Hey --

I'm trying to find how much space on the heap an object will take up. I'm basically trying to bypass constructors -- I have to create objects successfully, even if their constructors are:
this () { throw new Exception(); }

So, my strategy is to allocate enough space to hold the object and insert a pointer to the class's vtbl in the first sizeof(size_t) bytes of the allocated memory, then cast to the desired type. Which is pretty much what the 'new' keyword does. And I can find the vtbl easily enough. What about the amount of memory to allocate?

I can use Type.sizeof to get the size of the type on the stack.
I can use Type.classinfo.tsize() to get the size of the type on the stack.
I'm dealing with objects, so that's a constant -- it's (void*).sizeof.

Once I've allocated memory with the garbage collector, I can find the size of it with std.gc.capacity. So, I can find the size of any object I can create with a constructor:

T t = new T();
uint footprint = std.gc.capacity(*(cast(void**)(&t)));

I could go through T.classinfo.offTi:

auto capacity = std.gc.capacity(*(cast(void**)(&(new Object()))));
foreach (offti; T.classinfo.offTi) {
   capacity += offTi.ti.tsize();
}

Except offTi is empty, even if I add fields to the class.

Does anyone know how to get the allocated size of a class without instantiating it?
November 10, 2007
"Christopher Wright" wrote
> Does anyone know how to get the allocated size of a class without instantiating it?

if you are using D2.0, this should work I think:

size_t classSize = __traits(classInstanceSize, MyClass);

If using D 1.0, not sure :)

-Steve


November 10, 2007
Steven Schveighoffer Wrote:

> 
> "Christopher Wright" wrote
> > Does anyone know how to get the allocated size of a class without instantiating it?
> 
> if you are using D2.0, this should work I think:
> 
> size_t classSize = __traits(classInstanceSize, MyClass);
> 
> If using D 1.0, not sure :)

D'oh! Should've thought of that.

Thanks!

> -Steve
> 
> 

November 11, 2007
> Does anyone know how to get the allocated size of a class without instantiating it?

The comments page on classes suggests:

obj.classinfo.init.length
or
Class.classinfo.init.length

I didn't try it though.

Christian