T[new] misgivings

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Thu Oct 15 19:55:07 PDT 2009


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.

Me: T[new] is a container, therefore the assignment must resize the 
container from whatever size it had to 3 and then write 1, 2, 3 to its 
three slots.

I guess each of us has a point, but this is a setup for an increasingly 
unpleasant situation. Here's the dialog as it happened.

A: Ok, then how do I say the common operation "I want to overwrite 
whatever the array had with 1, 2, 3"? I can only presume there must be 
an obvious and simple way to do so, and I thought a = [1, 2, 3] was the 
obvious syntax to achieve that.

W: No, you must write

a[] = [1, 2, 3];

A: But that only works if the container already had length 3. So what I 
need to do is this:

a.length = 3;
a[] = [1, 2, 3];

A: But that is inefficient if the array had length less than 3 because 
it means double assignment

W: Nobody complained about it with slices.

A: So if I do want something that does the obvious operation "Whatever 
that array had, make it now have 1, 2, 3 as it contents" at a reasonable 
cost I need to call an elaborate function that is highly nontrivial to 
write?

W: Looks like so.

A: So then the first "Effective D" standard would have Item #1: "Avoid 
assignment to arrays. Call the assign() function"?

W: Nobody complained about it with slices.

===============

This goes into something more interesting that I thought of after the 
conversation. Consider:

T[new] a;
T[] b;
...
a = b;

What should that do?


Andrei



More information about the Digitalmars-d mailing list