T[new] misgivings
dsimcha
dsimcha at yahoo.com
Thu Oct 15 20:58:06 PDT 2009
== Quote from Andrei Alexandrescu (SeeWebsiteForEmail at erdani.org)'s article
> I talked to Walter about T[new] today and it seems we are having a
> disagreement.
> The problem is that I believe T[new] is a container, whereas Walter
> believes T[new] is nothing but a slice with a couple of extra operations.
> Paradoxically this seems to be conducive to subtle efficiency issues.
> For example, consider:
> int[new] a;
> ...
> a = [1, 2, 3];
> What should that do?
> Walter: T[new] is a slice with benefits, assignment for slices rebinds
> the slice, therefore the assignment must do the same. In this case, the
> assignments allocate a new array and make a refer to that array.
> Whatever old array a referred to will continue to live wherever it was.
But isn't part of the point of T[new] that you're supposed to only have one T[new]
pointing to any given block of memory? If you can bind a slice to a T[new], then
you can bind a slice to multiple T[new]s. Then you get back to having weird bugs
like:
immutable(int)[new] foo;
foreach(i; 0..5) {
foo ~= i;
}
immutable(int)[] bar = foo[0..4];
immutable(int)[new] baz = bar; // References the same memory as foo
baz ~= 666;
writeln(foo); // prints [1 2 3 4 666].
The only way around this would be something like COW semantics, i.e. you can
assign a slice to a T[new] w/o copying, but when you try to do anything with it
that couldn't be done w/ a slice, then it copies.
More information about the Digitalmars-d
mailing list