A r t i c l e s
Navigation

Note: This Wiki is
outdated, personal views
may have changed.
L505 A.I. bot is dead
long live THX 1138

M a i n P a g e

D i r e c t o r y

Returning Pointer or Object As Function Result


Returning pointers as function results or objects as function results can sometimes be confusing... since the programmer can be unclear about what is a valid pointer or what is a valid object to return.

Can a local pointer be returned safely.. and can a local object be returned safely.. may be the most confusing to some who are afraid of scope problems and invalid pointers or invalid references.

function something: TXyzObject;
var tmp: TXyzObject;
begin
  tmp:= TXyzObject.create;
  result:= tmp; 
end;
Above is a a valid object is then returned. Just remember that the object must be freed later, so write documentation stating so.. or name the function clearly such as CreateObject.

Similar rules apply when using the 'result' variable more directly:

function something: TXyzObject;
begin
  result:=TXyzObject.create;
end; 
Above is fine, but if you ever leave out the 'create' then you have no object, only an invalid pointer.

What about pointers or pointers to records for example:

function something: PXyzRecord;
var tmp: PXyzRecord;
begin
  new(tmp);
  result:= tmp; 
end;
Above is a a valid record on the heap that returned. Just remember that the record must be freed later, so write documentation stating so.. or name the function clearly such as CreateXyzRecord along with FreeXyzRecord. Or OpenConnect CloseConnection.. in other words use similar pairs of matching functions so the person knows they must free and create, or open and close, or init and fini.

How about using the result variable more directly:

function something: PXyzRecord;
begin
  new(result)
end; 
Above is fine, but if you ever leave out the 'new()' then you have an invalid pointer.

About
Note: This Wiki is outdated, personal views may have changed.

This wiki contains info on life, health, humans, nature, programming, database, fads, paradigms, poems, principles, theories.

Articles may contain statements which some may find helpful and encouraging, or even discouraging.

Beware, I believe in the Grand Justice system.
_ _ _