Unsure about validity of handle classes
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Jeroen Boschma
le 24 Oct 2015
Commenté : Jeroen Boschma
le 26 Oct 2015
Hi,
I just started using handle classes, and I'm unsure about one aspect. So a beginners question.. Assume I have two classes:
classdef my_class_A < handle
properties
X
end
methods
end
end
and a similar one for my_class_B. Then I do the following:
function test
clc
g = prepare_object;
g
function h = prepare_object
h = my_class_A;
h.X = my_class_B;
The main question is: is g valid? The underlying question: if prepare_object is called, where in memory are the classes stored which are created in there? If they are on the stack of prepare_object, then they are not valid anymore when the function returns and g points to useless junk. Or is the actual storage of my_class_A and my_class_B somewhere safe on the heap and they will remain safely there until I explicitly delete them myself?
Best regards,
Jeroen
0 commentaires
Réponse acceptée
Walter Roberson
le 24 Oct 2015
The space is allocated when their constructor is called. The space is removed by the garbage collector when the last handle to the space is removed. When you call prepare_classes the handles are returned in "h", which becomes "g" in the caller. So at that point there is still handles to the memory and those the contents can be displayed. After "test" returns there will be no more handles and the memory will be reclaimed.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Whos dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!