Unexpected behavior in classdefs that inherit from handle
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Roger Rouse
le 27 Sep 2023
Commenté : Roger Rouse
le 28 Sep 2023
I have a simple class, SomeClass, that inherits from handle.
I have another simple class, SomeOtherClass, that has a properity that is a SomeClass object.
When I instantiate two SomeOtherClass and set the value of the SomeClass property then both SomeOtherClass objects receive the value. I assume this is because both SomeOtherClass objects point to the same SomeClass object. But why? The two SomeOtherClass are separate instantiations. Please help me understand. The included code demostrates what I'm talking about.
Thanks, Roger
O1 = SomeClass;
O2 = SomeClass;
O3 = SomeOtherClass;
O4 = SomeOtherClass;
fprintf(1,'\nProperty Values After Instantiation\n');
worker(O1,O2,O3,O4);
O2.AProperty = pi;
fprintf(1,'\nProperty Values After Setting O2.AProperity to pi.\n');
worker(O1,O2,O3,O4);
O3.PropFromAbove.AProperty = exp(1);
fprintf(1,'\nProperty Values After Setting O3.PropFromAbove.AProperity to exp(1).\n');
worker(O1,O2,O3,O4);
fprintf(1,'\n!!! Why are O3.PropFromAbove and O4.PropFromAbove pointing to the same object!!!\n');
function worker(O1,O2,O3,O4)
parm = {'O1','O2'};
objs = {O1,O2};
for k = 1:numel(objs)
fprintf(1,'%s.AProperty = %f\n',parm{k},objs{k}.AProperty);
end
parm = {'O3','O4'};
objs = {O3,O4};
for k = 1:numel(objs)
fprintf(1,'%s.PropFromAbove.AProperty = %f\n',parm{k},objs{k}.PropFromAbove.AProperty);
fprintf(1,'%s.SomeOtherProp = %f\n',parm{k},objs{k}.SomeOtherProp);
end
end
0 commentaires
Réponse acceptée
Walter Roberson
le 27 Sep 2023
This is documented.
MATLAB evaluates a default expression when the property value is first needed (for example, when the class is first instantiated). The same default value is then used for all instances of a class. MATLAB does not reevaluate the default expression unless the class definition is cleared from memory.
So when you initialize a property to an expression that yields a handle, then the same handle will be used for all instances of the class.
If this is not what you want the you need to put in a constructor: constructors are run each time an object of the class is created.
Plus de réponses (0)
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!