[fpc-pascal] PChar & AnsiString
spir ☣
denis.spir at gmail.com
Tue Jun 1 17:13:56 CEST 2010
On Tue, 01 Jun 2010 15:00:47 +0100
Martin <fpc at mfriebe.de> wrote:
> On 01/06/2010 11:23, spir ☣ wrote:
> > What is the actual benefit of copy-on-write? I ask because of the following reasoning:
> > * If a string is just used at several places, for example in output or into bigger strings, then there is no reason reason to copy it into a new variable.
> > * If a programmer explicitely assigns an existing string to a new variable, the intent is precisely copy-semantics, to make them independent for further changes. If there is no change, there is also no reason for such an assignment.
[...]
> No, an assignment, or increase in ref count is not necessarily followed
> by a change:
>
> Procedure Foo(a:String);
> begin ... end;
>
> Procedure Bar;
> var s: string;
> begin
> s:= SomeString;
> Foo(s);
> end;
>
> Now a copy of s has to be given to Foo, because Foo *may* changes the
> string. But Foo may also *not* change the string => so leave it till later.
For me, parameter passing is just an implicit assignment "param:=s" (with the variant of var params). The same applies to return values when assigned back in calling code (*). I would have thus expected s the pointer to be passed. Just checked it is not the case. More secure, esp since legacy shortstrings do not behave that way.
This example rather backs my pov, I guess, since here copy-on-write does not apply. But it certainly could, since its application should prevent bad surprises, no? (unexpected change of original variable)
> Example 2:
>
> Procedure Bar;
> var a, b: string;
> begin
> a:= SomeString;
> b:=a;
> if SomeCondition then
> b:=b+"...";
> if SomeOtherCondition then
> b:=b+"???";
> end;
>
> So b may never be changed at all.
Sure, I did not mean this cannot happen. I rather spoke of the programmer's intent. My hypothesis is that it does not make sense to copy a string into another var if none will change. Your example is perfect :-) There are cases were this cannot be avoided.
Still, is this worth the complication of copy-on-write.
I also favor a super-simple and explicit coding style, which produces some more assignments, intermediate and not necessary, than clever coding with complex expressions. From this point of view, copy-on-write is an interesting scheme, in that it avoids useless copies (except for references), thus allowing such a coding style with minor penalty (ref copy only). But if the compiler is smart enough, such intermediate vars can probably be eliminated, no?
Denis
(*) And to some more constructs in other languages, like foreach (*the* feature I miss in freepascal):
foreach name in names do ... end;
________________________________
vit esse estrany ☣
spir.wikidot.com
More information about the fpc-pascal
mailing list