Destroying Objects
Object Lifecycle
An object's lifecycle ends when you reassign a new value to
that variable, when it is no longer used in a function, or when 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:
delete(hobj1)
hobj2.a
??? Invalid or deleted object.
Back to Top
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 =
BostonIf you call delete 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.
If you call delete on a value object, MATLAB returns
an error. You can only call clear on value objects.
Back to Top
 | Copying Objects | | Error Handling |  |
Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
Get the Interactive Kit