The demise of T[new]

Chris Nicholson-Sauls ibisbasenji at gmail.com
Mon Oct 19 12:32:22 PDT 2009


Andrei Alexandrescu wrote:
> Leandro Lucarella wrote:
>> Andrei Alexandrescu, el 19 de octubre a las 11:16 me escribiste:
>>>>>> I'm missing something? Why this shouldn't work?
>>>>> It may work, but I was unable to pull it off reasonably well.
>>>> What problems did you find?
>>> I thought I explained that above and in several other posts. I have
>>> the feeling this is going in circles, but let me add one more thing.
>>> People would want to have a reasonable way of choosing between
>>> T[new] and T[]. The differences between them are subtle (I have two
>>> tables showing the primitives of T[] and T[new], which are very
>>> similar).
>>
>> If T[new] is "array" and T[] is "slice" as I described them, I see no
>> subtlety, they are huge differences, one is a dynamic array, the other is
>> a view on somebody else's memory.
> 
> Their primitives overlap 90% in syntax and semantics.
> 
>> I know you probably hate when people says this (that's what I avoided
>> doing it before :):
>> I works very well in Python. You have arrays (well, lists, but the
>> interface is the same as an array) and slices. I never heard anybody
>> complaining about that being confusing.
> 
> Python lists and slices are quite different from D arrays.
> 
>>> That static decision concerns future appends to the array,
>>> which doesn't strike me as something you know from the get-go
>>> through future iterations of a design. Use of "auto" messes up
>>> things further: a nice function may choose to return T[new] because
>>> it just created an array (an implementation detail), but clients may
>>> find that unexpected.
>>
>> I don't see much problem. You should always return an array (T[new]) if
>> you have one, because you can get an slice from it (the inverse is not
>> true). Because of this, implicit conversion from array to slice can be
>> a good idea, so people expecting a slice when an array is returned will
>> never know an array was returned anyways. If you need to keep 
>> appending to
>> the array, you can have the original array and keep appending to it
>> without any performance hit (no copying, no new allocations).
>>
>> What's wrong with that?
> 
> People expecting a slice and using "auto" or templates are in for a rude 
> awakening.
> 
> 
> Andrei

I would argue that, if they truly *needed* a slice and are relying on "auto" then they 
implicitly accept responsibility for putting the [] in place to guarantee that.  In other 
words:
auto foo = someFunc()[];

Or T[]'s and T[new]'s could have an alternative to .dup that does the same thing (return 
self for T[], and return self[] for T[new]).  Either way, it would be something to point 
out in the book as a best practice: when expecting a slice, guarantee a slice with []'s.

-- Chris Nicholson-Sauls



More information about the Digitalmars-d mailing list