T[new] misgivings

Jason House jason.james.house at gmail.com
Thu Oct 15 20:45:38 PDT 2009


Andrei Alexandrescu Wrote:

> 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?

Allocate an array

 
> 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];

That matches my expectation

 
> 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

The optimizer should be able to make that efficient.



More information about the Digitalmars-d mailing list