Ranges require GC?

Marco Leise Marco.Leise at gmx.de
Tue Dec 10 14:20:54 PST 2013


Am Tue, 10 Dec 2013 19:55:20 +0100
schrieb "Adam D. Ruppe" <destructionator at gmail.com>:

> On Tuesday, 10 December 2013 at 18:54:54 UTC, Frustrated wrote:
> > I assume that ranges require the GC, is this true?
> 
> No, in fact, most ranges don't allocate at all.

"range" is just a concept and not a concrete type.
Functions that work on ranges identify them by specific calls
that can be made on them. (e.g. front, popFront(), length,
etc.). This is commonly known as duck-typing. And allows much
anything to be a range: Classes, structs, built-in arrays.

D objects and dynamic arrays are typically GC managed. Most
ranges returned from Phobos are implemented as structs though
and don't need a GC. If you write something like:

  [1,2,3].map!(a => a+1)()

then you are using a dynamic array ([1,2,3]) that will live in
the GC heap. "map" will then just return a range (implemented
as a struct). One has to understand that no memory will be
allocated to hold the result of the map process. In fact where
possible, Phobos returns lazily evaluated ranges that only
calculate the next item when you ask for it (using .front
and .popFront() on it).

-- 
Marco



More information about the Digitalmars-d-learn mailing list