Unsure about validity of handle classes

1 view (last 30 days)
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

Accepted Answer

Walter Roberson
Walter Roberson on 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.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!