关于TStringList.Assign方法复制机制及关联对象销毁的技术咨询
Great question—this is a common point of confusion with Delphi's TStringList, so let's break it down clearly:
Clarifying TStringList.Assign Behavior
First, let's resolve the ambiguity around the word "set" in the documentation: TStringList.Assign performs a deep copy of the source list's content, not a reference assignment. Here's what that means in practice:
- The target
TStringListcreates its own independent copy of all strings from the source. - If the source has associated objects (added via
AddObject), those objects are also copied (sinceTStringListsupports object associations). - The source
TStringListremains completely intact and separate from the target. Modifying the target afterAssignwon't affect the source, and vice versa. - Freeing the target
TStringListhas no impact on the source—they're distinct instances with their own allocated memory.
To confirm this behavior, here's a concrete example:
var SourceSL, DestSL: TStringList; begin SourceSL := TStringList.Create; try SourceSL.Add('Original Content'); DestSL := TStringList.Create; try DestSL.Assign(SourceSL); // Modify the target list DestSL[0] := 'Updated Content'; // The source remains unchanged ShowMessage(SourceSL[0]); // Outputs "Original Content" finally DestSL.Free; // Only destroys the target, source stays valid end; finally SourceSL.Free; end; end;
Understanding TStrings.AddObject & Object Ownership
The TStrings.AddObject documentation is explicit here: TStrings (and TStringList, which inherits from it) does NOT own the objects added via this method. This means:
- When you call
Freeon theTStringList, it only cleans up its own internal structures (the string list and references to associated objects)—it will not automatically free the objects you added. - Failing to manually free these objects will result in memory leaks.
To properly clean up, iterate through the list and free each associated object before freeing the TStringList:
var MySL: TStringList; I: Integer; begin MySL := TStringList.Create; try // Add objects to the list MySL.AddObject('Item 1', TObject.Create); MySL.AddObject('Item 2', TObject.Create); // Use the list for your logic... finally // First, free all associated objects for I := 0 to MySL.Count - 1 do MySL.Objects[I].Free; // Then free the list itself MySL.Free; end; end;
Key Takeaways
Assigncopies content, it doesn't link instances—source and target remain independent.- Always manually free objects added via
AddObjectbefore freeing theTStringListto avoid memory leaks.
内容的提问来源于stack exchange,提问作者Juan Jimenez
相关产品推荐
相关产品推荐

