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

Sean Kelly sean at f4.ca
Thu Apr 12 19:24:13 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.

See http://d.puremagic.com/issues/show_bug.cgi?id=88


Sean



More information about the Digitalmars-d mailing list