delphi object assign vs :=
Asked Answered
W

1

9

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 :=

Wesley answered 27/12, 2015 at 14:43 Comment(1)
Note that TObject does not have a Assign method, only TPersistent does. And the description of TPersistent.Assign talks about "similar" objects. Docs and contracts are a bit fuzzy here.Thacker
E
9
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?

Ezequiel answered 27/12, 2015 at 14:53 Comment(2)
Strings are not copied under assignment, but increment internal instance reference counter; same as dynamic arrays and (by default) interfaces.Tripe
@user246408 but it's worth to add: if string with refcount>1 is changed in some way, it is copied at last, so we get 2 separate strings in the end, so it's behaving just as if we had 2 independent strings from the beginning.Xanthate

© 2022 - 2024 — McMap. All rights reserved.