这段代码是否可以防止内存泄漏? s := TStringList.Create; // create first objecttry // Here line comes that seems to be dangerous s := GetSomeSettings; // Overrides reference to first object by second onefinally s.free; // Dest
s := TStringList.Create; // create first object try // Here line comes that seems to be dangerous s := GetSomeSettings; // Overrides reference to first object by second one finally s.free; // Destroying only second object, leave first object to live somewhere in memory end; function GetSomeSettings : TStringList; var rawString : string; settings : TStringList; begin // Singleton pattern implementation // Trying to find already existing settings in class variable settings := TSettingsClass.fSettings; // If there is no already defined settings then get them if not Assigned(settings) then begin GetSettingsInDB(rawString); TSettingsClass.fSettings := ParseSettingsString(rawString); settings := TSettingsClass.fSettings; end; Result := settings; end;
我想知道s:= GetSomeSettings;可能有害并忽略第一个对象,将其保存在记忆中?
是的,第1行创建的StringList被泄露.实际上,你在做:
s := TStringList.Create; s := AnotherStringList; AnotherStringList.Free;
至于GetSomeSettings例程:
通常,将新创建的实例作为函数结果返回是不明智或不鼓励的,因为您将所有权和销毁的责任转移到调用代码.除非你有一个机制/框架来处理它,这似乎是你的TSettingsClass的情况,但在这一小段代码中没有足够的证据.
然而,两段代码的组合显示出另一个问题:在s.Free之后,TSettingsClass.fSettings被销毁但不是nil.因此,第二次调用GetSomeSettings时,它返回一个悬空指针.