Re: pointer syntax
- From: "Maarten Wiltink" <maarten@xxxxxxxxxxxxxxxxxx>
- Date: Wed, 23 Nov 2005 17:23:50 +0100
"swansnow" <schultz@xxxxxxxxxxxxxxxxxxxxxxx> wrote in message
news:1132759180.698705.131050@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
[...]
> * Use var with objects, only if I intend to change the reference
> (beware of orphaned memory!)
Best practice is to avoid the issue altogether. People are sometimes
tempted to return a newly allocated object from a function, for example
a ListDirectory() function that uses a TStrings object to store the
filenames in.
What's bad about that is that the object's creation is in a different
scope than the object's destruction. This is asking for trouble. The
general pattern is
Obj:=ClassRef.Create;
try
Obj.Work;
finally
Obj.Free; Obj:=nil;
end;
and you can follow it in the above case by reading "Obj.Work" as
"ListDirectory(Obj);". The object is passed into the function, and
it fills the list for you.
procedure ListDirectory(const Names: TStrings);
var SearchResult;
begin
Names.BeginUpdate;
try
Names.Clear;
SearchResult:=FindFirst();
while (SearchResult.Found) do begin
Names.Add(SearchResult.Name);
FindNext(SearchResult);
end;
finally
Names.EndUpdate;
end;
end;
> * If I have anything else, use var if I need changes to come back.
> Avoid explicit pointers like the plague. (Again, unless I have some
> special reason to need them, like strange API calls:) )
There is a useful trick that can be played with C-style explicit
pointers and not with var parameters: you can pass null as the pointer.
If you're not interested in the function's results but only in its
side effects, this frees you from having to allocate a buffer where
the result will be stored, only to be thrown away immediately.
In the above code, consider the effect of passing in nil as the
parameter. Of course, the receiving code has to check for this every
time. Equally of course, the above function has no side effects so no
functionality is left. That's not the point; it didn't compile anyway.
Groetjes,
Maarten Wiltink
.
- References:
- pointer syntax
- From: swansnow
- Re: pointer syntax
- From: Maarten Wiltink
- Re: pointer syntax
- From: swansnow
- Re: pointer syntax
- From: Maarten Wiltink
- Re: pointer syntax
- From: swansnow
- pointer syntax
- Prev by Date: Re: Loaded memory image differs from map file
- Next by Date: Re: Writing Binary Files with TFileStream
- Previous by thread: Re: pointer syntax
- Next by thread: Re: pointer syntax
- Index(es):
Relevant Pages
|