필터 지우기
필터 지우기

classes with static (constant) properties

조회 수: 82 (최근 30일)
Florian B
Florian B 2021년 8월 5일
댓글: Florian B 2021년 8월 7일
How do I define static class properties that are accessed without allocating the object?
By object I mean class instance. I would just need constant properties (snippet below) but would also like to know how it would work for non-static properties too. I definetely prefer method 2 over 1 but calling foo.prop1 may create a temporary object tmp of class foo. In detail: The call of prop1 is the made via tmp. After the value of prop1 has been returned, the temporary object tmp is destroyed (deallocated). The described behavior would cause a small but significant load on performance/memory that can accumulate when one uses method 2 a lot or very often.
Method 1 has its own problems, where one is definitely that complicated construction of the member with a function and a persistant variable.
classdef foo
% METHOD 1:
% static function, defines local persistent var that is returned on each call
% Upside: definitely static, no object instantiation
% Downside: little overhead (function call, var is set every call)
% Rem. quest: Name of persistent var must be unique in whole workspace?
methods (Static)
function out = prop1()
persistent prop1_loc;
prop1_loc = 1;
out = prop1_loc;
end
end
% METHOD 2:
% Constant properties that can be accesses in the same manner as the static function
% Upside: Simple, shorter that method 1.
% Downside: None, unless the object is not instantiated by a call of foo.prop1
% Rem. quest: Does call to prop allocate an object (class instance)?
properties(Constant)
prop1 = 1;
prop2 = 2;
end
end
%%%%%%%% %%%%%%%%
%called like
x = foo.prop1;
func(foo.prop1);

채택된 답변

Matt J
Matt J 2021년 8월 5일
편집: Matt J 2021년 8월 5일
No, an object is not created with method 2. An easy way to verify that is with the following small test class. You can see that the constructor is never called when the constant property is accessed.
>> myclass.prop
ans =
0
classdef myclass
properties (Constant)
prop=0;
end
methods
function obj=myclass
disp 'Constructing' %Alert us if constructor is called.
end
end
end
  댓글 수: 1
Florian B
Florian B 2021년 8월 7일
Completely logical. Should have found that solution myself but I have not used constructors in MATLAB classes yet.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Construct and Work with Object Arrays에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by