Is it advisable to have a handle object inside a handle object?

2 Ansichten (letzte 30 Tage)
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

Akzeptierte Antwort

Guillaume
Guillaume am 25 Jan. 2017
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 Kommentare
Walter Roberson
Walter Roberson am 25 Jan. 2017
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
Guillaume am 25 Jan. 2017
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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by