D vs. placement new (for classes) aka why D needs .sizeof and .alignof for classes (values not references)

Chris Nicholson-Sauls ibisbasenji at gmail.com
Thu Apr 12 17:05:37 PDT 2007


Forest Ray wrote:
> Before I add this to the bug database I wanted to run this by everyone and see if I'm overlooking something.  Classes in D are always a reference.  Therefore the .sizeof and .alignof a class (reference) are always (void*).sizeof and (void*).alignof.  D allows the class allocator (new) to be overloaded.  The number of bytes required to hold the class (value) is passed as the first parameter to new(size_t size).  This works well unless you are wanting to perform a placement new.  When using placement new you pass in the storage for the object to be placed.  
> 
> new(size_t size, void* ptr) {
>     return ptr;
> }
> 
> The problem is at compile time you can NOT determine the size or alignment of a class (value), only the reference.  Therefore you can not know the sizeof the buffer to preallocate to hold the class (value).  I believe this to be an oversight in the language design.  The alignment issue is easier to overcome, the ABI states the first field of a class (value) is the vbtbl pointer which will always mean the class (value) is (void*).alignof aligned.  The .sizeof property for a class (value) is not available, here in lies the problem.  Placement new is the easy example where the sizeof the class (value) is needed.  Also consider the case of a blocks of class (values) being preallocated for a free list.
> 

Given:
class Foo { ... }
auto obj = new Foo;

There is:
obj.sizeof

Which you know, and does as you say.  But then there is:
obj.classinfo.init.sizeof

Which will render the actual size of class instances.  :)  Granted it isn't very pretty, 
but it works.  What _would_ be nifty, would be if one could use 'Foo.sizeof' (invoke 
.sizeof on the type rather than the variable) to get the same value.  Ie, make 
Class.sizeof an alias to Class.classinfo.init.sizeof -- I don't think this would be a 
problem.  In the meantime, the .classinfo trick is your friend.

-- Chris Nicholson-Sauls



More information about the Digitalmars-d mailing list