Unsure about validity of handle classes

1 次查看(过去 30 天)
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

采纳的回答

Walter Roberson
Walter Roberson 2015-10-24
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Whos 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by