Understanding object deletion for user defined classes

조회 수: 10 (최근 30일)
Otis
Otis 2012년 3월 29일
I'm sorry for such a broad question but I'm having trouble finding a decent explanation of how objects are deleted or what happens when objects are deleted (and in particular, user defined objects), i.e. what is Matlab's garbage collection process. For example, suppose I create an instance of MyObject, which is a hypothetical class may contain lots of data including other objects.
A = MyObject();
If I need to create a new instance of MyObject and I don't need the old instance anymore, how do I do so and ensure all the memory used by A gets cleared, all objects within A get deleted, any files that may have been opened get closed, you name it? Do I need to set A to []? Do I need to call "clear A"? Will setting just setting A to MyObject() in another statement be enough?
I've noticed that the "Handle" class has a method called "delete." Am I required to subclass delete and add all the garbage collection there? If so, must I called garbage collection explicitly or will Matlab call it for me (say in the cases I mentioned in the previous paragraph)?
A link to an existing explanation of all this would suffice.
A very large number of "Thank you"'s to anyone who can answer this for me.
Bill

채택된 답변

per isakson
per isakson 2012년 3월 29일
The design goal of The Mathworks is that we, the users, should not need to bother about memory management - I believe.
There have been (are still?) bugs (e.g. #498418) causing the warning "Warning: Objects of href=""</a> class exist. Cannot clear this class or any of its super-classes."
The blog post Considering Performance in Object-Oriented MATLAB Code states "[...]MATLAB doesn't use garbage collection to clean up objects periodically but instead destroys objects when they first become unreachable by any program.[...]"
See also the blog post Understanding Object Cleanup
The blog post Keeping Things Tidy describes how to close files on deletion of objects.
The R2012a documentation covers most of your questions and more.
Overloading the delete method of handle is useful to close files, etc., but not needed to recover the memory of the instance.
Just setting A to MyObject should be fine.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Construct and Work with Object Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by