加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 10:19:50 所属栏目:大数据 来源:网络整理
导读:我刚刚调试一个问题,一个函数返回一个字符串,让我担心。我一直假设返回一个字符串的函数的隐式Result变量在函数调用开始时为空,但是下面的(简化的)代码产生了一个意想不到的结果: function TMyObject.GenerateInfo: string; procedure AppendInfo(const
我刚刚调试一个问题,一个函数返回一个字符串,让我担心。我一直假设返回一个字符串的函数的隐式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。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读