Is it advisable to have a handle object inside a handle object?
1 次查看(过去 30 天)
显示 更早的评论
Hi,
I would like to create two classes, say, class1 and class2 both of which inherit from the handle class. Therefore I have
classdef class1 < handle
properties
prop1
end
end
classdef class2 < handle
properties
prop2
end
end
Now suppose I create an instance for each of the classes, say a1=class1 and a2=class2. Is it advisable to set
a1.prop1=a2
a2.prop2=a1
?. That is, I have put each object inside each other. The advantage of this strategy is that I can easily manipulate a2 from within the body of a1 and vice versa. The problem, I don't know whether it is really a problem, is the clear circularity or infinite loop this strategy creates: a1 is inside a2 which is inside a1, inside a2,...
Is this advisable to do this? Is there an alternative way of dealing with this? i.e. being able to manipulate each object from within the body of the other.
Thanks
0 个评论
采纳的回答
Guillaume
2017-1-25
Such coupling between two classes is usually indication of a flaw in your object model. Sometimes, it is the most efficient solution. What is your use case? Normally, one object is clearly the container for the other.
I'm not sure how matlab memory manager copes with such coupling as Mathworks does not document how it works, so if you do implement this, you need to implement a delete method in both objects that make sure to clear the reference to the other object. Otherwise as you say you have circularity. Perhaps matlab's memory manager can cope with that (it detects that neither object is accessible from the main workspace?), perhaps not.
8 个评论
Walter Roberson
2017-1-25
Philip, that implies that MATLAB uses a mark/sweep algorithm along with reference counting. That possibility is something that I have not seen any previous evidence for, and have seen evidence against for regular data. Is the mark/sweep exclusive to handle class?
Guillaume
2017-1-25
It certainly would be great if details of the memory management for classes were actually documented (in the doc not on the website or forums) so that those of us that are used to having to deal with this in other languages don't have to wonder how it works in matlab.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Graphics Object Programming 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!