有人能帮我解释一下为什么在底层函数抛出异常时,TStrings被返回为“无法访问的值”吗?
function GetStrings():TStrings;
begin
result := TStringList.Create;
try
raise exception.Create('Error Message');
except
FreeAndNil(result);
raise
end;
end;
procedure TFormMain.Button1Click(Sender: TObject);
var
S : TStrings;
begin
try
S := GetStrings;
try
//Do awesome stuff
finally
FreeAndNil(S)
end;
except
//Debug watch: S = "Inaccessible value"
Assert(S = nil, 'Assertion failure, S should be nil');
end;
end;
如果我在重新引发异常之前不调用FreeAndNil(result);
,函数GetStrings
也会返回 "无法访问的值"。但是这样一来,我就有了一个内存泄漏问题:-O