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

2 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Guillaume
Guillaume el 25 de En. de 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 comentarios
Walter Roberson
Walter Roberson el 25 de En. de 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 el 25 de En. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by