Destroying Objects

Object Lifecycle

An object's lifecycle ends when:

  • You reassign a new value to that variable.

  • The object is no longer used in a function.

  • Function execution ends.

MATLAB® handle classes have a special method called delete that MATLAB calls when a handle object lifecycle ends.

Calling delete on an object explicitly makes all copies of a handle object invalid because it destroys the data associated with the object and frees memory used by deleted objects. MATLAB calls delete automatically so it is not necessary for you to do so. Classes can redefine the handle class delete method to perform other cleanup operations, like closing files or saving data.

Deleting a handle object renders all copies invalid:

hobj1 = HdClass(8);
hobj2 = hobj1;
delete(hobj1)
hobj2.Data
Invalid or deleted object.

Difference Between clear and delete

The handle class delete method removes the handle object, but does not clear the variable name. The clear function removes a variable name, but does not remove the values to which the variable refers. For example, if you have two variables that refer to the same handle object, you can clear either one without affecting the actual object:

hobj = containers.Map({'Red Sox','Yankees'}, {'Boston','New York'});
hobj_copy = hobj;
clear hobj
city = hobj_copy('Red Sox')

city =

Boston

If you call clear on all handle variables that refer to the same handle object, then you have lost access to the object and MATLAB destroys the object. That is, when there are no references to an object, the object ceases to exist.

On value objects, you can call clear to remove the variable. However, MATLAB does not automatically call a value class delete method, if one exists, when you clear the variable.

Was this topic helpful?