Skip to content

SpecificationIX · Objects

9.6

Copies, references and identity

Assigning an object does not duplicate it: it gives another name to the same object. To get a new object with the same data you need Copiar.

Markdown version

9.6.1 How it works

Not all values behave the same when assigned:

ValueWhen assigned or passed by value
numbers, booleans, characters and textscopied: changing the source does not affect the copy
objectsshared: both names see the same object
arrayspassed by reference

Copiar(object) creates a new object of the same class without running the constructor, and copies a single level: primitive attributes are copied, and those that are references stay shared with the original.

ProgramAn alias and a copy

Class Mochila
  Define dueno As String;
  Define libros As Integer;
EndClass

Algorithm Copias
  Define a As Mochila <- New Mochila();
  a.dueno <- "Ana";
  a.libros <- 3;
  Define alias As Mochila <- a;
  Define copia As Mochila <- copy(a);
  alias.libros <- 5;
  copia.libros <- 9;
  Write a.libros, " ", alias.libros, " ", copia.libros;
  Write a = alias, " ", a = copia;
EndAlgorithm

Output

5 5 9
true false

The program finishes normally.

  1. 1alias <- a creates nothing: two arrows to the same object.

  2. 2Copiar(a) creates a second object with the same values.

  3. 3Changing alias.libros is visible through a; changing copia.libros is not.

Figure 9.6-1.a and alias point to the same object; copia points to another one with the same data at first.

a and alias point to object 1 with owner Ana and 3 books. Copiar creates object 2 with the same data, pointed to by copia. Afterwards object 1 has 5 books and object 2 has 9.

9.6.2 Identity

Every object or array has an identity: the order number in which it was created during the run. The first is 1, the next 2, and so on. Identity never changes and is never reused, even after the object is no longer used. = between objects compares identities: that is why a = copia is False even though they hold the same data.

Reference cycles —an object pointing to another that points back to the first— are valid.

In short

  • Primitives and texts are copied; objects are shared.
  • Copiar creates a new object and copies a single level.
  • Identity is the creation order and is never reused.
  • = between objects compares identity, not contents.