const challenge

Derek Parnell derek at psych.ward
Sun Feb 3 00:11:42 PST 2008


On Sun, 3 Feb 2008 07:44:03 +0000, Janice Caron wrote:

> On 2/2/08, Derek Parnell <derek at psych.ward> wrote:
>> void main()
>> {
>>     string s;
>>     char[] t;
>>     char[] u = "hello" ~ s ~ t;
>>
>>     writefln("%s", u);
>> }
>> c:\temp>dmd test
>> c:\dmd\dmd\bin\..\..\dm\bin\link.exe test,,,user32+kernel32/noi;
>>
>> c:\temp>test
>> hello
> 
> Bah! Dangnabbit! OK then - /this/ doesn't compile:
> 
>>     string s;
>>     char[] t;
>>     string u = "hello" ~ s ~ t;

Of course it doesn't. As far as I can recall, D has always said that
concatenation creates a dynamic array, and since 'const' has been in use,
that array is also a mutable one.

> ... the string version doesn't compile, and that's just
> as bad. The error message indicates that the compiler can't convert a
> char[] to an invariant(char)[], which means that the type of the RHS
> is now deemed to be char[].

Well its not so much that it can't convert it, but more that it won't
convert it implicitly; you have to be explicit.

Try this instead ...

     string s;
     char[] t;
     string u = ("hello" ~ s ~ t).idup;


We have to be aware that the rule in D is that RHS concatentation always
produces a mutable dynamic array, so if we want it to be immutable we need
to be explicit about it. Maybe smart compilers can even avoid redundant
copying if they see the ".idup" operation in this context.

> (In previous releases, I'm sure it would
> have been const(char)[], but I see nothing in the change log to
> account for it. Maybe it's I who's going mad?)

I don't think it (the RHS formed by concatenation) was ever a const thingy.

-- 
Derek Parnell
Melbourne, Australia
skype: derek.j.parnell



More information about the Digitalmars-d mailing list