Search code examples
matlabshallow-copycopy-on-write

Shallow copy behavior in MATLAB


Lots of people bump into unexpected shallow copy behavior when they start off in Python, and I'd like to make sure I don't make any of those mistakes in MATLAB (with which I have less experience).

I read this article about object behaviors in MATLAB and I read this question that pertains to pointer/handle behavior. Are there any situations where isa(obj, 'handle') would return false but you would still encounter the situation where modification of obj would result in the modification of another variable (to my knowledge, any argument modification by a function call should trigger a copy on write and duplicate the variable in memory)?

Is this a complete understanding of "shallow copy"-like behavior in MATLAB? Are there any additional caveats to standard value object copy behavior?


Solution

  • A value class can contain a handle class, and if you modify it you will change the instance of the handle class. For example (note that containers.Map is a built-in class that is a handle - nothing special about it, I just chose it for convenience:

    >> a = containers.Map; a('hello') = 1;
    >> b = struct('field1', 1, 'field2', a);
    >> isa(b, 'handle')
    ans =
      logical
       0
    >> b.field2('hello') = 2;
    >> a('hello')
    ans =
         2
    

    So b is a struct (which has value semantics), but one of its fields contains a containers.Map, which is a handle and has reference semantics. When you modify that field, you also change a, which is another reference to the underlying containers.Map.