Setting array length to 0 discards reserved allocation?

Chris Cain via Digitalmars-d digitalmars-d at puremagic.com
Thu Jul 24 16:39:26 PDT 2014


See this post:
http://forum.dlang.org/thread/shpcpmwvphbyaumxghsd@forum.dlang.org

My response in that thread:
----
The reason is simple, observe:

auto arr = [1,2,3]

It is safe if you append 4 to that.

auto arr = [1,2,3,4]
auto other = arr[];
arr.length = 2;

It is *not* safe to append 5 to arr here, because doing so would
change other to [1,2,5,4] which is (probably) not what you want
(or, at least, you haven't made it explicit that you're okay with
this behavior). Since slices are unaware of whether other views
on memory exist, they must always reallocate if they've been
shrunk to avoid the possibility of overwriting existing elements
in other views of the array.

When you use "assumeSafeAppend", you are guaranteeing that either
no other views exist, or if they do exist that you don't care if
they are overwritten. Take note that the second case is *really
bad* if your element type is immutable, for obvious reasons.
----


More information about the Digitalmars-d mailing list