OSNews article about C++09 degenerates into C++ vs. D discussion

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Mon Nov 20 08:25:26 PST 2006


Miles wrote:
> Frits van Bommel wrote:
>> Array slicing, for one.
>> While technically possible with malloc, it would require maintaining a
>> reference count and an extra pointer to the start of the allocated
>> memory area to call free() on. And that still doesn't solve the problem
>> of cyclic references (if the array doesn't just contain primitive data),
>> as well as requiring synchronization in multi-threaded applications.
> 
> Ok, I see.
> 
> But looking at the problem, being someone from algorithms, I think it is
> possible and feasible to implement array slicing using malloc
> allocation. An extra field will be needed anyway since you need
> reference count for the array, just put it along with the beginning of
> the array and only a single pointer will be needed for both reference
> count and beginning of array.

With malloc/refcounting you need:
For every allocation:
* Reference count (possibly in array)
* Some kind of synchronization structure. (may be just a bit in the 
refcount, since 31 bits is probably enough :) )
In every reference:
* Pointer to array (for refcount & free when refcount == 0)
* Pointer to start of slice
* Length of slice or pointer to end of slice (or one byte further)

Current D implementation has (AFAIK):
* No extra overhead per allocation
In every reference:
* Pointer to start of slice
* Length of slice

So malloc/refcount takes an extra 4 bytes per allocation (assuming 
32-bit refcount + synch) plus an extra 4 bytes per _reference_ (assuming 
32-bit pointer). (on top of synch issues discussed below)

> Cyclic references is a problem only when using GC. If the programmer
> wants to use a malloc-based allocation, he knows he should handle cyclic
> references himself. Not a problem.

Actually, cyclic references are not a problem for GC. Not having to 
handle them is in fact one of the benefits of GC, or (depending on how 
you look at it), having to handle them is a problem with reference counting.

> As for synchronization, I think this is more a problem when GC is used
> than when it is not. Malloc-based allocation needs synchronization, of
> course, but I think GC-based does also. Deallocation is very atomic and
> can be implemented without synchronization and still be thread-safe.
> GC-based, OTOH, needs to freeze the whole application (not just the
> threads doing allocation) in order to collect.

I wasn't talking about allocation, I was talking about slicing arrays, 
copying of references, passing references as parameters, deleting 
objects containing references, returning from functions holding 
references and returning references. (though return-value optimization 
may remove that last one, if only one reference to it existed in the 
function)



More information about the Digitalmars-d mailing list