Get class size of object

Adam D. Ruppe destructionator at gmail.com
Sun Aug 11 10:48:59 PDT 2013


On Sunday, 11 August 2013 at 17:28:33 UTC, JS wrote:
> What's the difference between init.length and classInstanceSize?


classInstanceSize is based on the static type, whereas typeid() 
fetches the dynamic type. Consider the following:

===
void showSizes(Object obj) {
    import std.stdio;
    writeln("Static size: ", __traits(classInstanceSize, 
typeof(obj)));
    writeln("Actual size: ", typeid(obj).init.length);
}

class Foo {
   int a;
   int b;
}

void main() {
    Foo foo = new Foo();
    showSizes(foo);
}
===

// note this would be 4 bytes for the monitor, 4 bytes for the 
vtable pointer
Static size: 8

// this is the size of the parent class, Object, plus the size of 
Foo's members
Actual size: 16


The difference is because showSizes statically only knows how to 
deal with the specific type written (Object), but it is legal to 
pass any derived objects to that function too. Since child 
classes can add more members, their sizes can change.

typeid() gets information about the specific instance, so it 
gives accurate details about the child class. typeof() and 
__traits always work on the static type.

> The class instance size must be known at compile time

Unless you have the specific static type (in that case, use a 
template instead of a virtual function), you can't do that. 
Consider this:

===
auto lib = new SharedLibrary("plugin.dll");
auto create = cast(Object function()) 
lib.getProcAddress("createObject");

if(create !is null) {
    Object o = create();
    // what is o?
}
===


This plugin, by its nature, couldn't be known at compile time. It 
might not even exist yet at the time you're compiling the 
application!

The dll could write its own class though - the function might 
look like this:

===
module plugin;

class CoolPlugin {
    int a;
    int b;
    override string toString() {
       return "I have two members!";
    }
}

export Object createObject() {
    return new CoolPlugin();
}
===


And there's no way for you to know how big CoolPlugin is at 
compile time. You can't see that code at all to know these 
details.

At runtime, however, it is doable - that's where the typeid() 
comes in. It looks up the automatically generated run time type 
information.


More information about the Digitalmars-d-learn mailing list