The demise of T[new]

Steven Schveighoffer schveiguy at yahoo.com
Tue Oct 20 12:29:03 PDT 2009


On Tue, 20 Oct 2009 14:43:16 -0400, Bill Baxter <wbaxter at gmail.com> wrote:

> On Tue, Oct 20, 2009 at 11:30 AM, Andrei Alexandrescu
> <SeeWebsiteForEmail at erdani.org> wrote:
>> Steven Schveighoffer wrote:
>>>
>>> If your goal is to affect the original array, then you should accept a  
>>> ref
>>> argument or not append to it.
>>
>> I think that's an entirely reasonable (and easy to explain) stance.
>
> I've definitely spent time tracking down exactly such bugs, where I
> meant to make the argument a ref but didn't.  If the above is to be
> the official stance, then I think it should be enforced by the
> compiler.  Appending to non-ref slice args should be an error.

Except when you are passing ownership of an array.  Basically, there are  
four modes:

T[] x : a) you are passing ownership to the function, and the array might  
not be deterministically usable after the function returns, e.g. T[]  
padAndCapitalize(T[]).  Usually such functions' return values are  
deterministic, and the focus of what you care about.

   -or-
         b) you are lending ownership to the function, only the array  
elements will be altered, e.g. replace().

ref T[] x : You are lending ownership of the array to the function, but  
you get ownership back, e.g. push().  Fully deterministic altering.

const(T)[] x : You retain ownership of the array, the function cannot  
alter it, e.g. toUpper().

So it's not possible to flag on the signature between the first a) and b)  
modes, we must currently rely on documentation.  But the "append and  
modify" routines are pretty rare.

Essentially, what you want is a type where the length is const, but the  
data is mutable.  I think creating such a type should be possible in the  
library.

But fixing the append problem alone is a huge step forward, since all of  
these cases could result in corruption of totally unrelated data if the  
arrays were appended to.  Especially the const version is bad.

-Steve



More information about the Digitalmars-d mailing list