Borrar filtros
Borrar filtros

Unsure about validity of handle classes

1 visualización (últimos 30 días)
Jeroen Boschma
Jeroen Boschma el 24 de Oct. de 2015
Comentada: Jeroen Boschma el 26 de Oct. de 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

Respuesta aceptada

Walter Roberson
Walter Roberson el 24 de Oct. de 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.

Más respuestas (0)

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by