newObj := TMyObject.Create; newObj.Assign(oldObj);
Assuming Assign is running correctly, this
- creates a new instance of
TMyObject (via Create ) - stores the link to this instance in the variable
newObj (via the operator := ) - Performs a deep copy of
oldObj , making newObj functionally accurate copy of oldObj (via Assign ).
The end result here is that you have two completely separate instances of TMyObject , which at the moment are exact copies of each other.
newObj := oldObj;
The above just copies the link to oldObj and stores it in the newObj variable. In this case, you have only one instance of TMyObject , and both the newObj and oldObj point to the same instance. If you change the state of this object using any variable, both will reflect these changes, since both of them point to the same underlying object.
This contradicts the above example, where you have two separate objects whose state can diverge, since both objects change independently.
Conceptually, object (class) variables are commonly referred to as "reference types." Variables of this type are essentially just pointers (if this is more familiar). An assignment ( := ) with reference types copies only the reference to the object, not the object itself.
The only significant exception is string types, which have many properties of reference types, but are controlled by the compiler to also behave in many ways as value types (changing a line creates a new modified copy, rather than modifying the original string, which can be referenced elsewhere )
See also: To copy one object to another, is it possible to directly assign variables or should I assign their properties individually?
J ...
source share