const challenge
Steven Schveighoffer
schveiguy at yahoo.com
Mon Feb 4 07:01:06 PST 2008
"Steven Schveighoffer" wrote
> "Derek Parnell" wrote
>> On Sun, 3 Feb 2008 08:43:54 +0000, Janice Caron wrote:
>>
>>> On 2/3/08, Derek Parnell wrote:
>>>> 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.
>>>
>>> I don't think that's true. Back in November, Steven Schveighoffer
>>> wrote this post:
>>> http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D&article_id=61276
>>>
>>> Stephen was finding he needed to explicitly .dup to get a mutable
>>> result.
>>
>> With respect and meaning no offense, however even though that post of
>> Steven's says...
>>
>>>> auto a2 = a1 ~ "\n";
>>>> Now, a2 is declared as a const(char)[] array,
>>
>> He has not shown any evidence that that is actually the case. It could
>> be that he is assuming that to be the case, because each attempt I have
>> made to duplicate his assertion has just shown me that the compiler
>> regards 'a2' as mutable.
>>
>> The current D2 compiler treats 'a2' as mutable.
>>
>
> I probably should respond to this :)
>
> D2 at the time did have an issue with a similar statement. I don't know
> if that's the case now, but it was the basis for my bug report (1654).
> What triggered me to write the post is that at the time I was attempting
> to port tango to D 2 (I think it was 2.006 or 2.007), and there was a
> piece of a function that attempted to add a string literal to the end of a
> const or mutable char array (can't remember which), and since 2.x has
> strings as invariant, the compiler was complaining. I was forced to do a
> dup, or needlessly initialize a dynamic array. I may have misrepresented
> the exact problem, which may have lead to me posting valid code, sorry
> about that. I thought I had posted the correct thing.
>
> I believe that the return value of any concatenation operation should be
> mutable, as it always creates a new copy. The issue becomes when you are
> dealing with only invariants, i.e.:
>
> string s = "hello" ~ " world";
>
> Now, if the concatenation operation returned a mutable string, then you
> need an explicit cast. However I think the problem is being worked on by
> Walter and Andrei.
>
> -Steve
I just tested this out in D 2.006, and you are correct. a1 ~ "\n" results
in a char[]. I think when I was porting the code, it looked more like:
a1 ~ '\n';
which results in a const(char)[].
So the example I gave originally is invalid, but the point is not. The
result of concatenation should be determined by the usage of the result, and
allowed if it doesn't break constness.
-Steve
More information about the Digitalmars-d
mailing list