delphi object assign vs :=

Dinesh M picture Dinesh M · Dec 27, 2015 · Viewed 7.9k times · Source

Could someone explain the difference between:

(1.)

newObj := TMyObject.Create;
newObj.Assign(oldObj);

and

(2.)

newObj := oldObj;

in 2. does newObj and oldObj refer to the same single object?

Sorry if this has been covered before but is is difficult to search :=

Answer

J... picture J... · Dec 27, 2015
newObj := TMyObject.Create; 
newObj.Assign(oldObj);

Assuming that Assign is implemented correctly, this

  • creates a new instance of TMyObject (via Create)
  • stores a reference to that instance in the variable newObj (via the := operator)
  • Performs a deep copy of oldObj, making newObj a functionally exact copy of oldObj (via Assign).

The end result here is that you have two completely separate instances of TMyObject which are, at this point, exact copies of each other.


newObj := oldObj;

The above simply copies a reference to oldObj and stores it in the variable newObj. In this case you still only have one instance of TMyObject and both variables newObj and oldObj point to the same instance. If you modify the state of that object using either variable, both will reflect those changes since they both point to the same underlying object.

This is in contrast to the example above where you have two separate object whose state can diverge as both objects are modified independently.


Conceptually, variables of objects (classes) are generally referred to as "reference types". Variables of this type are essentially just pointers (if this is more familiar). Assignment (:=) with reference types only copies the reference to the object, not the object itself.

The only material exception to this are string types, which have many properties of reference types, but are managed by the compiler to also behave in many ways as value types (modifying a string produces a new modified copy rather than modifying the original string which may be referenced elsewhere).

See also : To copy from one object to another, can I assign the variables directly, or must I assign their properties individually?