MATLAB Object-Oriented Programming

(Joyce) #1
Destruction of Objects with Cyclic References

Consider a set of objects that reference other objects of the set such that the references
form a cyclic graph. In this case, MATLAB:


  • Destroys the objects if they are referenced only within the cycle

  • Does not destroy the objects as long as there is an external reference to any of the
    objects from a MATLAB variable outside the cycle


MATLAB destroys the objects in the reverse of the order of construction. for more
information, see “Handle Object During delete Method Execution” on page 7-17.

Restrict Access to Object Delete Method


Destroy handle objects by explicitly calling delete on the object:

delete(obj)

A class can prevent explicit destruction of an object by setting its delete method
Access attribute to private. However, a method of the class can call the private
delete method.

If the class delete method Access attribute is protected, only methods of the class
and of subclasses can explicitly delete objects of that class.

However, when an object lifecycle ends, MATLAB calls the object’s delete method when
destroying the object regardless of the method’s Access attribute.

Inherited Private Delete Methods

Class destructor behavior differs from the normal behavior of an overridden method.
MATLAB executes each delete method of each superclass upon destruction, even if that
delete method is not public.

When you explicitly call an object’s delete method, MATLAB checks the delete method
Access attribute in the class defining the object, but not in the superclasses of the object.
A superclass with a private delete method cannot prevent the destruction of subclass
objects.

Declaring a private delete method makes most sense for sealed classes. In the case where
classes are not sealed, subclasses can define their own delete methods with public access.

7 Value or Handle Class — Which to Use

Free download pdf