Bug: class field modified by reference

17 visualizaciones (últimos 30 días)
Antonio Mei
Antonio Mei el 1 de Jun. de 2018
Comentada: Antonio Mei el 1 de Jun. de 2018
There is a major bug in Matlab in which the field of a class is modified when passed as an function argument but not requested as an output if the calling function modifies the value internally. In the minimal example below: b.value is not the same before and after calling test.
b.value = 10;
b.value,
a = test(b);
b.value
function a = test(b)
a=1; b=b.value*10;
end
  3 comentarios
Antonio Mei
Antonio Mei el 1 de Jun. de 2018
Right, it only happens for when b is defined via classdef.
Walter Roberson
Walter Roberson el 1 de Jun. de 2018
Please post actual example including classdef

Iniciar sesión para comentar.

Respuesta aceptada

Steven Lord
Steven Lord el 1 de Jun. de 2018
I tried this with a very simple class and it worked as I expected.
It sounds to me like b is an instance of a handle class. If that's the case, the behavior you described is correct as described in the "Handle Objects Modified in Functions" section on that documentation page (assuming that in your test function you assigned into the value property of the b object rather than overwriting the variable inside the function.) See the attached example. I expect the last line printed when you run that code to be "ans = 100".
  1 comentario
Antonio Mei
Antonio Mei el 1 de Jun. de 2018
Thank you for clarifying. I actually had used the "dynamicprops" property. Do you know of a way to dynamically define properties without recursing to a handle subclass?

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Construct and Work with Object Arrays en Help Center y File Exchange.

Productos


Versión

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by