Search code examples
delphiassigntstringlist

Does the Assign method of TStringList copy the list of strings from source to destination, or does it simply copy the pointers?


I'm having trouble with the vague terminology of the documentation of the TStringList.Assign method. The word "set" in

If Source is of type TStringList, the list is set to the list of the source TStringList object, and if associated objects are supported, any associated objects are copied from Source as well.

can be interpreted in multiple ways. Is the TStringList object copied from the source to the destination, leaving the source intact... or is the destination set to point to the source object without copying anything? The implication of the latter is that if I then free the destination object, the source object is also freed. Or?

This statement in the documentation for TStrings.AddObject, which is how the Strings are added to the destination, further muddies the waters for me:

Note: The TStrings object does not own the objects you add this way. Objects added to the TStrings object still exist even if the TStrings instance is destroyed. They must be explicitly destroyed by the application.

Does this mean that I have to do more than calling .Free to destroy the destination TStringList when I am done with it?


Solution

  • TStringList.Assign() copies the strings and object pointers from the source TStringList. Just know that this is a shallow copy not a deep copy, since string is a reference-counted type.