In Matlab I have a class
classdef myClass
properties
% some properties here...
end
methods ( Access = 'public' )
function obj = myClass()
% constructor...
end
function obj = delete( obj )
% suppose to be destructor...
fprintf(1, 'delete\n');
end
end % public methods
end
What is the default behavior of Matlab when I clear
a variable of type myClass
?
For example:
>> m = myClass();
>> clear m
I would expect Matlab to call the destructor of m
at this stage, but it seems like it doesn't!!
My questions:
How can I force a call to the destructor when
clear
ing a variable?Is this default behavior of Matlab's makes any sense? Isn't it more logical to call the destructor when
clear
ing a variable?Is it possible that Matlab's classes do not have a detructor method (that is, there is no default method to be called when the class is destroyed)? Or am I missing something?
Is it possible that only classes derived from
handle
have a destructor (thedelete
method)?
Thanks!
EDIT : following Jonas' answer, a brief summary:
Matlab has two types of classes: value classes (the default) and handle classes (derived from handle
super class). Value classes tends to provide better performance, however, they do not have a destructor functionality.
handle
classes do have a destructor function: delete
that is called when the class is destroyed. See this question from more details on handle
class destructors.
If one wishes to have a destructor-like functionality for value classes, Jona's answer proposes a method utilizing onCleanup
functionality.
Thanks for the good answer and the insightful comments!