unsafe toString() behavior

BCS BCS_member at pathlink.com
Tue Jun 27 01:02:31 PDT 2006


In article <op.tbshnsu0po9bzi at moe>, Chris Miller says...
>
>On Tue, 27 Jun 2006 00:44:05 -0400, BCS <BCS_member at pathlink.com> wrote:=
>>
>> IM(h)O toString should *always* return a copy.
>>
>
>Nah, I disagree. Take MemoryStream for example, what if it has 2MB, you
>want that copied every toString. This COW is just a different method than
>what's common in other languages, and yields such a great performance 
>boost. If you want a copy, copy it. But if all you want to do is read the
>value, what is the point in copying.
>

Overrides of object.toString might not be a good candidate for always copy, but
toSting(intType) will copy in most cases (~ always copies) but an implementation
might return a ptr to a static array for some cases (0-9 in the following
example);

char[] toString(uint i);
{
char[] ret;
const static char[] map = "0123456789";
ret = map[i%10..i%10+1];
i/=10;
while(i)
{
ret = map[i%10..i%10+1] ~ ret;
i/=10;
}
return ret;
}

This would be a bad choice for COW, forget it once and problems start cropping
up all over the place. A Simpler implementation might still get unrolled to
this.

>Plus, where does this copying stop? Should every function returning an
>array, or even a reference, make sure the caller gets a copy he can modify?
>

No, only when it is ALWAYS a bug if the referenced data is changed.





More information about the Digitalmars-d-bugs mailing list