Delphi:for循环期间函数结果未清空
这正常吗Delphi:for循环期间函数结果未清空,delphi,function,stack,Delphi,Function,Stack,这正常吗 for a := 1 to 10 do x.test; x.test; x.test; x.test; function test: string; begin {$IFDEF DEBUG} DebugMessage('result check = '+Result,3); {$ENDIF} result := result + 'a'; end; 10:39:59: result check = 10:39:59: result chec
for a := 1 to 10 do
x.test;
x.test;
x.test;
x.test;
function test: string;
begin
{$IFDEF DEBUG} DebugMessage('result check = '+Result,3); {$ENDIF}
result := result + 'a';
end;
10:39:59: result check =
10:39:59: result check = a
10:39:59: result check = aa
10:39:59: result check = aaa
10:39:59: result check = aaaa
10:39:59: result check = aaaaa
10:39:59: result check = aaaaaa
10:39:59: result check = aaaaaaa
10:39:59: result check = aaaaaaaa
10:39:59: result check = aaaaaaaaa
10:39:59: result check =
10:39:59: result check =
10:39:59: result check =
在for循环期间未释放函数结果堆栈?:O嗯,您应该始终初始化函数结果。不要仅仅因为它是动态(在本例中为字符串)类型就假定它将被设置为正确的值。
结果
被视为函数的隐式var
参数
想象一下,如果你这样明确地写出来:
procedure test(var result: string);
begin
result := result + 'a';
end;
for i := 1 to 10 do
test(s);
然后您希望它附加到s
每次调用时都会丢弃结果
,这就是为什么编译器有时会决定最终确定它。正如@gabr所指出的,作为优化,它选择在循环中不最终确定这个隐式变量
如果每次调用test
时都将test
的结果分配给一个字符串,那么每次都会看到该字符串变长,它将永远不会被重新初始化
这就是为什么您应该始终初始化结果变量的原因。它看起来像一个局部变量,但最好将其视为一个
var
参数。+1作为示例,但请将您对我现在删除的答案所做的注释包含在您的答案中(如果您将结果分配给函数之外的某个对象,则初始化将只发生一次
)@Cosmin已经在那里了,但我现在把它作为一个新的段落(倒数第二段)脱颖而出@DavidHeffernan,回答得很好!今天,我遇到了类似的动态数组问题,很容易修复,但这帮助我真正理解。这在之前的SO中已经处理过。然后编译器应该发出“未初始化”警告,就像非生存期托管类型一样。