T[new] misgivings

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Fri Oct 16 07:00:27 PDT 2009


Don wrote:
> Max Samukha wrote:
>> On Thu, 15 Oct 2009 21:55:07 -0500, Andrei Alexandrescu
>> <SeeWebsiteForEmail at erdani.org> wrote:
>>
>>> I talked to Walter about T[new] today and it seems we are having a 
>>> disagreement.
>>
>> I'd prefer Walter's way with a provision that array literals are
>> immutable and allocated statically:
>>
>> immutable(int)[] a = [1, 2, 3]; // no allocation here
>> int[new] b = [1, 2]; // new storage is allocated and the literal is
>> copied there
>> int[] a = [1, 2, 3]; // error. dup needed
>> auto c = [1, 2, 3]; // c is of type immutable(int)[]
>> b[] = c; //b's length is changed and c's contents  copied to b's
>> storage
>> auto d = [1, 2, 3].dup; // d is of type int[new]
>> auto e = [1, 2, 3].idup; // e is of type immutable(int)[new]
>>
>> // arrays are true reference types
>> int[new] a = [1, 2, 3];
>> b = a;
>> a.length = 22;
>> assert (a.length == b.length);
> 
> This makes perfect sense to me. The rule would be:
> If 'x' is T[new], then:
> x = y; _always_ copies y into a {length, capacity-specified block}, 
> unless it already is one. x is given a pointer to the start of that block.
> x[] = y[]; does a memcpy, regardless of whether y is a T[new] or a T[].

It makes sense to make array literals immutable. The trouble is you 
won't be able to create arrays of most interesting types that way.

class Widget { ... }
Widget w1, w2, w3;
auto arr = [ w1, w2, w3 ]; // error!

Walter brought up the same argument at some point. He compared array 
literals with string literals. No! String literals only contain 
statically-known characters. Array literals may contain anything.


Andrei



More information about the Digitalmars-d mailing list