size of a class instance
Bill Baxter
dnewsgroup at billbaxter.com
Tue Nov 14 00:13:02 PST 2006
Lionello Lunesu wrote:
> Sean Kelly wrote:
>> Bill Baxter wrote:
>>> Is this really the best way to get the size of a class instance given
>>> the type?
>>>
>>> MyClass.classinfo.init.length;
>>
>> Yes. And this only works at run time. I proposed a new .isizeof
>> property to simplify things, but it didn't seem terribly popular. See:
>>
>> http://d.puremagic.com/issues/show_bug.cgi?id=88
>>
>>
>> Sean
>
> I suppose sizeof(MyClass) could simply return the right value. I don't
> see how the size of a class' handle can be useful.
>
> L.
I suspect the reason is that for doing various low-level things you
might actually need to know how much space the thing is occupying on the
stack. Like a varargs, for instance. You need to know how big the
thing is on the stack to advance the _argptr properly. It doesn't
matter how big the instance data on the heap is.
I just now did a web search to see what other GC languages that hide
pointers from you do.
Java just doesn't have sizeof apparently.
C# has it. From the spec:
"For all other (non predefined types), the result of the sizeof
operator is implementation-defined and is classified as a value, not a
constant.
...
When applied to an operand that has struct type, the result is the total
number of bytes in a variable of that type, including any padding."
So basically it sounds like they say you can't count on sizeof(aclass)
returning anything in particular.
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.
--bb
More information about the Digitalmars-d-learn
mailing list