struct vs. class, int vs. char.

grauzone none at example.net
Tue Apr 28 11:58:56 PDT 2009


Denis Koroskin wrote:
> On Tue, 28 Apr 2009 22:13:50 +0400, Tomas Lindquist Olsen <tomas.l.olsen at gmail.com> wrote:
> 
>> On Tue, Apr 28, 2009 at 6:07 PM, MLT <none at anon.com> wrote:
>>> 2. char[] vs. int[]
>>> I think it is strange that
>>> char[] x = "1234" ;
>>> x[0] = '4' ;
>>>
>>> Produces a run time error, but
>>> int[] x = [1,2,3,4] ;
>>> x[0] = 4 ;
>>> Doesn't. I think that they both should, or both shouldn't - to be  
>>> consistent (and it would be better if they both didn't). Best would be  
>>> again, to allow the programmer to specify where the array (or other  
>>> stuff) should be stored.
>>>
>> It pretty much boils down to this (mostly said in other replies)
>>
>> * string literals are special, they are allocated in a static data
>> segment, readonly if the platform allows it.
>>
>> * arrayliterals as non-static expressions are always heap allocated.
>> even when there's absolute no need for it... (see
>> http://d.puremagic.com/issues/show_bug.cgi?id=2356 )
>>
>> -Tomas
> 
> Someone ought to post a feature request to make arrayliterals immutable by default (D2 only, I don't think this change will go to D1 anyway) and don't heap-allocate them every time they're used:
> 
> int[] x1 = [1,2,3,4]; // error: can't assign immutable(int)[] to int[]

Why not auto-allocate? Writing that .dup all the time is going to be 
annoying. Just implicitly convert it from immutable to mutable by copying.

> int[] x2 = [1,2,3,4].dup; // okay, allocates
> 
> int[4] x3 = [1,2,3,4]; // okay, doesn't allocate
> 
> foreach (int i; [1,2,3,4]) { // okay, doesn't allocate
>     // ...
> }



More information about the Digitalmars-d mailing list