manual memory management
Jonathan M Davis
jmdavisProg at gmx.com
Tue Jan 8 16:50:19 PST 2013
On Wednesday, January 09, 2013 00:37:10 Joseph Rushton Wakeling wrote:
> On 01/08/2013 10:43 PM, Jonathan M Davis wrote:
> > std.container.Array and built-in arrays are _very_ different. Array is a
> > container, not a range. You can slice it to get a range and operate on
> > that, but it's not a range itself.
>
> Is there a particular reason why Array can't have a range interface itself?
It's a container. Turning a container into a range is just begging for
trouble. For instance, what happens when you iterate over it? You remove all
of its elements, because you keep calling popFront on it. Making a container
into a range is an incredibly bad idea. Things are already weird enough with
the built-in arrays.
> > On the other hand, built-in arrays aren't true containers. They don't own
> > or manage their own memory in any way, shape, or form, and they're
> > ranges.
> Forgive the naive question, but what _is_ the definition of a 'true
> container'? Is managing its own memory a necessary component? Or just for
> D's concept of a container?
A container owns and manages its elements. It may not manage their memory
(e.g. it could all be garbage collected, or if its elements are references or
pointers, it's really the references or pointers that it owns and manages, not
what they point to, so it's not managing the memory that they point to). This
is in direct contrast to a slice which is simply a view into a container. You
can mess with a slice as much as you want without altering the container
itself. It's just that altering the elements in the slice alters those in the
container, because they're the same. You can also have multiple slices which
view the same container. But you only have one copy of a given container, and
so it's the owner of its elements. Copying the container would mean copying
the elements themselves, whereas copying a slice would only copy the state of
the view into the container and wouldn't copy any elements at all.
A container contains elements. A slice is a view into a container and doesn't
actually, technically contain them. It has no control over their memory or
existence whatsoever. It only provides a way to view them.
A lot of what makes D arrays (and therefore ranges) so confusing is the fact
that arrays don't own their elements. They're slices. It's the runtime that
owns and manages the elements. But people think of arrays as being containers,
so they end up getting confused.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list