Is it advisable to have a handle object inside a handle object?
조회 수: 2 (최근 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에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!