V2 string

Derek Parnell derek at nomail.afraid.org
Wed Jul 4 23:11:35 PDT 2007


On Thu, 05 Jul 2007 04:44:41 +0300, Vladimir Panteleev wrote:

> On Thu, 05 Jul 2007 02:23:11 +0300, Derek Parnell <derek at psych.ward> wrote:
> 
>> This leads to constructs like ...
>>
>>    char[] result;
>>
>>    result = SomeTextFunc(data).dup;
> 
> Is SomeTextFunc allocating a copy of the string which it is returning?
> If it is, then there's no reason why it should return a "string" type. 
> If it isn't, then modifying the data in the returned char[] could have
> unforeseen consequences.

Yes, I realize this and I'm not saying its doing the wrong thing, and
actually I'm not even complaining. I'm just letting people know some of the
observations I've had in moving to v2. In this case, someone has to copy
the resulting data - either the function that created it or the routine
that called the function. If the called function does the duplication, it
could be a waste if the calling function is not going to further modify it,
that is why I elected to pass a 'const' reference to the new data. The
calling function can then decide if it needs a copy (to modify it) or not.

   string result;
   result = SomeTextFunc(data); // no need to dup if I'm not changing it.


I've got a set of alias to help me ...

   alias char[]  text;
   alias wchar[] wtext;
   alias dchar[] dtext;

so now I see 'text' as mutable and 'string' as immutable.

>> Another commonly used idiom that I had to stop using was ...
>>
>>    char[] txt;
>>    txt = getvalue();
>>    if (wrongvalue(txt))
>>        txt = ""; // Reset to an empty string
> 
> Since empty string literals don't really point to data, I'd 
> suggest that empty string and array literals shouldn't be
> const/invariant in favor of the above example. It breaks some
> consistency, but "a foolish consistency is the hobgoblin of
> little minds" ;)

Nice idea, but I can't see it happening because of the inconsistency angle.

Instead I've decided to use the idiom ...

    text txt;
    txt = getvalue();
    if (wrongvalue(txt))
        txt = text.init; // Reset to an empty string
  
-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
5/07/2007 3:52:27 PM



More information about the Digitalmars-d mailing list