Unsure about validity of handle classes

2 ビュー (過去 30 日間)
Jeroen Boschma
Jeroen Boschma 2015 年 10 月 24 日
コメント済み: Jeroen Boschma 2015 年 10 月 26 日
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.
  1 件のコメント
Jeroen Boschma
Jeroen Boschma 2015 年 10 月 26 日
Thanks for the answer Walter.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by