Understanding object deletion for user defined classes
5 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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.[...]"
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 Center 和 File 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!