delphi – 初始化字符串函数结果?

前端之家收集整理的这篇文章主要介绍了delphi – 初始化字符串函数结果?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我刚刚调试一个问题,一个函数返回一个字符串,让我担心。我一直假设返回一个字符串的函数的隐式Result变量在函数调用开始时为空,但是下面的(简化的)代码产生了一个意想不到的结果:
function TMyObject.GenerateInfo: string;

        procedure AppendInfo(const AppendStr: string);
        begin
          if(Result > '') then
            Result := Result + #13;
          Result := Result + AppendStr;
        end;

begin
  if(ACondition) then
    AppendInfo('Some Text');
end;

多次调用函数导致:

"Some Text"

第一次,

"Some Text"
"Some Text"

第二次,

"Some Text"
"Some Text"
"Some Text"

第三次等。

解决它,我不得不初始化结果:

begin
  Result := '';
  if(ACondition) then
    AppendInfo('Some Text');
end;

是否有必要初始化一个字符串函数结果?为什么(在技术上)?为什么编译器不发出警告“W1035函数’xxx’的返回值可能未定义”用于字符串函数?我需要通过我的所有代码,以确保一个值被设置为不可靠的期望一个空字符串的函数,如果结果没有明确设置?

我在一个新的测试应用程序测试这个结果是一样的。

procedure TForm1.Button1Click(Sender: TObject);
var
  i: integer;
  S: string;
begin
  for i := 1 to 5 do
    S := GenerateInfo;
  ShowMessage(S); // 5 lines!
end;

解决方法

这不是一个错误,而是“ feature”:

For a string,dynamic array,method
pointer,or variant result,the
effects are the same as if the
function result were declared as an
additional var parameter
following the
declared parameters. In other words,
the caller passes an additional 32-bit
pointer that points to a variable in
which to return the function result.

也就是说你的

function TMyObject.GenerateInfo: string;

真的是这样:

procedure TMyObject.GenerateInfo(var Result: string);

注意“var”前缀(不是“out”,你可能会期望!)。

这是不直观的,所以它导致代码中的所有类型的问题。有问题的代码 – 这个功能的结果的一个例子。

看到并投票选举this request

原文链接:https://www.f2er.com/delphi/103612.html

猜你在找的Delphi相关文章