Reading about D: few questions

Jonathan M Davis jmdavisProg at gmx.com
Fri Dec 23 15:20:07 PST 2011


On Friday, December 23, 2011 20:19:28 Mr. Anonymous wrote:
> I saw that std.string functions use assumeUnique from std.exception.
> As for your example, it probably should be:
> 
> char[] endWithDot(const(char)[] s)
> {
>      return s.dup ~ '.';
> }

No, that allocates _two_ strings - one from dup and one as the result of the 
concatenation. It should either be

auto retval = s.dup;
retval ~= '.';
return retval;

or

return cast(char[])(s ~ '.');

The problem is that because s is const(char)[], the result of the 
concatenation is that type. But it's guaranteed to be a new string, so the 
cast is fine. It's arguably better to use the first version though, since it 
doesn't require a cast.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list