string types: const(char)[] and cstring

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Tue May 29 13:17:40 PDT 2007


Reiner Pope wrote:
> Frits van Bommel wrote:
>> For other cases though, I could see how a "unique" (or similar) type 
>> constructor that would allow implicit conversion to both mutable and 
>> invariant (and const) types could be useful.
>> For instance, if the strings in your example were replaced by mutable 
>> arrays, a "unique char[]" return value of .dup could then be assigned 
>> to mutable/const/invariant references without needing casts.
> Funny, that's just what I thought of (including the name unique).

I'm pretty sure this has been suggested in these newsgroups in the past, 
including using "unique" as the keyword.

> When I 
>  first thought about it, I thought that such a construct would be very 
> useful and very powerful, but I can't actually think of any use cases 
> except with .dup and other constructor-type functions. (Although 
> supporting them should alone be enough motivation).

Some use cases I can think of:
* Obviously, builtin array property .dup, as you mentioned.
* std.utf.toUTF* (except the non-converting ones such as char[] -> char[])
* The result of certain operator overloads (arithmetic in a bignum 
class, opCat in a string class, the result of the builtin ~ operator for 
arrays)
* Lots of stuff in std.string: join, split, maketrans, all the toString 
overloads, format, succ, abbrev. (AFAIK all of these are guaranteed to 
return a unique array)
* toString overloads for classes that return the result of any of the 
above[1] (especially builtin ~ and std.string.format are often useful in 
toString, in my experience).

As you can see, there are plenty of cases where newly allocated objects 
or arrays are returned.


[1]: This one would require the ability to add "unique" in an overridden 
method, since it's a bad idea to require it of all classes. This could 
be considered to fall under the category of covariant return values.



More information about the Digitalmars-d-announce mailing list