Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value of function might be undefined

Tags:

delphi

Ok, I have the following function:

function TfPackagedItemEdit.GetRTFDescription: TStringList;
begin
  Result.Text := richDescription.Lines.Text; //stringlist
end;

The compiler generates the following warning about this line:

[DCC Warning] W1035 Return value of function 'GetRTFDescription' might be undefined

Any ideas on how I can clear up this warning? (other than just turning it off in the project options)

I've tried:

function TfPackagedItemEdit.GetRTFDescription: TStringList;
begin
  Result.Text := '';
  Result.Text := richDescription.Lines.Text;
end;

But that doesn't work either.

like image 805
croceldon Avatar asked Jun 10 '09 18:06

croceldon


1 Answers

The Result variable is not initialized by default. It doesn't automatically refer to some compiler-generated TStringList instance. You need to assign a value to Result. That means having a line like this somewhere in your code:

Result := ...;

An expression like Result.X is reading the value of Result in order to get a reference to its X member, so you need to have given Result a value already. Larry's answer demonstrates how to do that. It generates a new TStringList instance, so the caller of this function needs to call Free on that object sometime.

But in a comment, you mention that you're using this function as a property accessor. It's inconvenient for callers to have to free objects every time they read a property, so your whole plan might be inappropriate. Since it looks like you're trying to expose the description text, you might want to consider this instead:

function TfPackagedItemEdit.GetRTFDescription: TStrings;
begin
  Result := richDescription.Lines;
end;

Notice first that I've changed the return type to TStrings, which is essentially the abstract base class of all kinds of string lists throughout the VCL. TStringList is one descendant, but TRichEdit.Lines doesn't use TStringList. Instead, it uses a specialized TStrings descendant that knows how to interact with the underlying rich edit control.

Next, notice that I have not created any new objects. Instead, I have returned a reference directly to the control's Lines property. Users of your RTFDescription property no longer need to worry about freeing the object they get.

like image 58
Rob Kennedy Avatar answered Oct 05 '22 11:10

Rob Kennedy