Do I have to delete object created at runtime?

1 view (last 30 days)
Herbert
Herbert on 21 Nov 2014
Edited: Adam on 21 Nov 2014
Assuming that I have a class like this:
classdef myBlubbClass < handle
properties
bla = myBlaClass.empty(1,0);
end % end of properties
methods
function someMethod( obj, x )
for i = 1:x
obj.bla( i ) = myBlaClass( i, 'test' );
end
end % end of someMethod
end % end of methods
end % end of classdef
where several "myBlaClass" objects are created and then stored in "bla". Do I have to treat those object in a special way? e.g. deleting them explicitly in the destructor of "myBlubbClass" ?
Thanks for your help in advance!

Answers (1)

Adam
Adam on 21 Nov 2014
Edited: Adam on 21 Nov 2014
handle-derived objects will get garbage collected when no references exist to them any more. You can add your own 'delete' function (make sure you get the right syntax else it will not be picked up as the destructor if you want to clean some stuff up on deletion (e.g. removing listener handles or closing a figure), but if there is nothing you want to explicitly do you don't need to add the delete function.
I do sometimes explicitly delete objects with
delete( myObject )
which will clear the object out straight away, but unless they are proving a big problem and causing memory leaks I often just leave it to the garbage collector if I don't have a specific reason for killing an object right away.
To deal with your more specific question, is myBlaClass also handle-derived? If so then you can delete it in the destructor if you want, but be careful as there may be places elsewhere that also have "pointers" (lapsing into C/C++ there, but really I just mean references to the same objects) to those instances if you give public access to them. If they are entirely private to your myBlubbClass then there isn't a problem - you can delete them explcitly, but equally they should get garbage collected on destruction of your myBlubbClass object anyway.

Categories

Find more on Construct and Work with Object Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!