How do you remove/insert elements in a dynamic array without allocating?
Malte Skarupke
malteskarupke at web.de
Thu Nov 8 18:05:30 PST 2012
On Wednesday, 7 November 2012 at 09:45:48 UTC, monarch_dodra
wrote:
> On Wednesday, 7 November 2012 at 03:45:06 UTC, Malte Skarupke
> wrote:
>> Having no clear ownership for the array is not something I am
>> willing to accept.
>
> "Strong ownership" puts you back into C++'s boat of "bordering
> psychotic duplication on every pass by value". In a GC
> language, and in particular, D, that favors pass by value, this
> might not be the best approach.
>
> I'll re-iterate that you may consider looking into
> std.container.Array. It behaves much like would std::vector
> (reserve, etc)... You can extract an actual range from Array,
> but there is a clear "container" - "range" distinction.
>
> An added bonus is that it uses "implicit reference" semantics.
> This means that when you write "a = b", then afterwards, you
> have "a is b", and they are basically alias. This is a good
> thing, as it avoids payload duplication without your explicit
> consent. The implicit means that it will lazily initialize if
> you haven't done so yet.
>
> You claim you want "explicit ownership": Array gives you that,
> but not in the classic RAII sense. If you need to duplicate an
> Array, you call "dup" manually.
>
> --------
> Also, Array uses a deterministic memory model, just like
> vector, that releases content as soon as it goes out of scope.
> I could have done without that, personally, but to each their
> own.
I think we have just had different experiences. In my experience
a shared_ptr is usually not what you want. Instead I prefer a
unique_ptr in many cases. Just because multiple things are
referencing your data, that doesn't mean that they should all
share ownership of it.
For me well defined ownership is just good coding practice,
similar to the const keyword. I've seen it prevent bugs and
therefore I use it for all cases that I can. I prefer to have
those exceptions where I can not have clear ownership stand out,
rather than them being the norm.
More information about the Digitalmars-d
mailing list