Delphi:函数for循环期间没有清空 [英] Delphi: function Result not emptied during for loop
问题描述
是否正常?
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
function result stack is not freed during a for loop? :O
推荐答案
结果
被视为隐式 var
参数到你的函数。
Result
is treated as an implicit var
parameter to your function.
想象一下,如果你这样明确写出来:
Imagine if you wrote it out explicitly this way:
procedure test(var result: string);
begin
result := result + 'a';
end;
for i := 1 to 10 do
test(s);
然后你会期望它附加到 s
。
Then you would expect it to append to s
.
每次你调用它时,你都会抛出 Result
这个事实是为什么编译器有时会决定完成它正如@gabr所指出的那样,它作为优化选择不在循环内完成这个隐式变量。
The fact that you are throwing away Result
each time you call it is why the compiler sometimes decides to finalise it. As @gabr points out, it elects not to finalize this implicit variable when inside a loop as an optimisation.
如果要分配 test
到每个你调用 test
的字符串,那么你会看到字符串每次都变长,它永远不会被重新初始化。
If you were to assign the result of test
to a string every time you called test
then you'd see the string get longer each time, it would never be re-initialized.
这就是为什么你应该总是初始化你的结果变量。它看起来像一个局部变量,但最好被认为是一个 var
参数。
This is why you should always initialize your result variable. It looks like a local variable, but it is best thought of as a var
parameter.
这篇关于Delphi:函数for循环期间没有清空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!