问题描述
我刚刚调试了一个函数,该函数返回的字符串让我很担心。我一直认为返回字符串的函数的隐式Result变量在函数调用开始时为空,但是以下(简化的)代码产生了意外的结果:
函数TMyObject.GenerateInfo:字符串;
过程AppendInfo(const AppendStr:string);
if(Result>’’)开始
然后
Result:= Result +#13;
结果:=结果+ AppendStr;
结尾;
开始
if(ACondition)然后
AppendInfo( Some Text);
结尾;
多次调用此函数会导致:
某些文本
第一次,
某些文本
某些文本
第二次,
某些文本
某些文本
某些文本
第三次,等等。
要修复它,我必须初始化结果:
开始
结果:='';
if(ACondition)则
AppendInfo( Some Text);
结尾;
是否需要初始化字符串函数结果?为什么(技术上)?为什么编译器不针对字符串函数发出警告 W1035函数 xxx的返回值可能未定义?我是否需要遍历所有代码以确保设置了一个值,因为如果未显式设置结果,从函数中期望一个空字符串是不可靠的?
我已经在一个新的测试应用程序中对此进行了测试,结果是相同的。
过程TForm1.Button1Click(Sender: TObject);
var
i:整数;
S:字符串;
for i:= 1至5开始
做
S:= GenerateInfo;
ShowMessage(S); // 5行!
结尾;
这不是错误,而是 :
即您的
函数TMyObject.GenerateInfo:string;
这真的是:
过程TMyObject.GenerateInfo(var结果:字符串);
请注意前缀 var (而不是 out
这是 SUCH 不直观,因此会导致代码中出现各种问题。有问题的代码-此功能结果的一个示例。
查看并投票给。
I've just been debugging a problem with a function that returns a string that has got me worried. I've always assumed that the implicit Result variable for functions that return a string would be empty at the start of the function call, but the following (simplified) code produced an unexpected 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;
Calling this function multiple times resulted in:
"Some Text"
the first time,
"Some Text"
"Some Text"
the second time,
"Some Text"
"Some Text"
"Some Text"
the third time, etc.
To fix it I had to initialise the Result:
begin
Result := '';
if(ACondition) then
AppendInfo('Some Text');
end;
Is it necessary to initialise a string function result? Why (technically)? Why does the compiler not emit a warning "W1035 Return value of function 'xxx' might be undefined" for string functions? Do I need to go through all my code to make sure a value is set as it is not reliable to expect an empty string from a function if the result is not explicitly set?
I've tested this in a new test application and the result is the same.
procedure TForm1.Button1Click(Sender: TObject);
var
i: integer;
S: string;
begin
for i := 1 to 5 do
S := GenerateInfo;
ShowMessage(S); // 5 lines!
end;
This is not a bug, but "feature":
I.e. your
function TMyObject.GenerateInfo: string;
Is really this:
procedure TMyObject.GenerateInfo(var Result: string);
Note "var" prefix (not "out" as you may expect!).
This is SUCH un-intuitive, so it leads to all kind of problems in the code. Code in question - just one example of results of this feature.
See and vote for this request.
这篇关于初始化字符串函数结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!