Finding the allocated size of a class?

Christopher Wright dhasenan at gmail.com
Sat Nov 10 08:11:50 PST 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?


More information about the Digitalmars-d-learn mailing list