You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于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 TStringList creates its own independent copy of all strings from the source.
  • If the source has associated objects (added via AddObject), those objects are also copied (since TStringList supports object associations).
  • The source TStringList remains completely intact and separate from the target. Modifying the target after Assign won't affect the source, and vice versa.
  • Freeing the target TStringList has 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 Free on the TStringList, 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

  • Assign copies content, it doesn't link instances—source and target remain independent.
  • Always manually free objects added via AddObject before freeing the TStringList to avoid memory leaks.

内容的提问来源于stack exchange,提问作者Juan Jimenez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 13:52:42