[fpc-pascal] Functions with out parameters

Jonas Maebe jonas.maebe at elis.ugent.be
Mon Mar 10 14:56:27 CET 2008


On 10 Mar 2008, at 14:19, Damien Gerard wrote:

> If you have this, the showmessage display an empty string and  
> sometimes the app crashes. I had a doubt so I tried this :
>
> procedure AnotherMethod;
> var s, t: UTF8String;
> begin
>  s := 'Some text';
>  t := s;
>  Foo(t, s);
>  // Do something with `s`
> end;
>
> And it works well the app never crash and all my variables are  
> correct. So I guess the two parameters share the same pointer. It  
> seems logic to me in this case.

It's not really about the same pointer, but about the reference count.  
Ansistrings/UTF8Strings are reference counted. If you pass one as out  
parameter, then before the call the reference count of the out  
parameter is decreased before the call. If it had a reference count of  
only one, this will cause it to be freed at that point.

> However, is there a way the compiler produces an error in this case ?

It would only be possible in very few cases, where (like in your case)  
you are using the same literal expression twice (and even then it's  
only wrong if the reference count of the string pointed to by that  
expression is one). More often than not the problem is that the same  
string is passed in already via different var/const parameters, so the  
equality cannot be detected at a syntactic level.

> I suppose there is a similar case with the 'var' keyword.

In case of a var parameter, the reference count of the argument is not  
decreased in advance. There you can indeed still have the problem  
later on inside the body of the called function if you overwrite the  
var parameter and then still use the const parameter later on (again,  
if the passed argument had a reference count of 1).



More information about the fpc-pascal mailing list