gnychis
gnychis

Reputation: 7555

way to copy a class that is a Handle Class?

I have a class that is by handle, and I want to copy it by value and store it somewhere. However, if I change anything in the class, it also changes the copy of it.

Here is an example of my class I want to copy:

classdef MyClass < handle
    properties
        data;
    end
    methods
        function M = MyClass()
           M.data=5; 
        end
    end      
end

Here is a test class to test changes:

classdef Test < handle  
    properties 
        store 
    end 
    methods 
         function N = Test(M) 
             N.store = M; 
         end 
    end 
end 

Now, we create an instance of MyClass and store it in Test:

>> m=MyClass
m =
  MyClass handle
  Properties:
    data: 5
  Methods, Events, Superclasses

>> a=Test(m)
a = 
  Test handle
  Properties:
    store: [1x1 MyClass]
  Methods, Events, Superclasses

>> a.store
ans =
  MyClass handle
  Properties:
    data: 5
  Methods, Events, Superclasses

Finally, if I change the value of 'data' in 'm' I do NOT want it to change the value in store, however it seems like MyClass is stored in 'store' by reference:

>> m.data=3;
>> a.store
ans = 
  MyClass handle
  Properties:
    data: 3
  Methods, Events, Superclasses

>> a.store.data
ans =
     3

Is it possible to copy a "handle" class? Or do I need to change my class to make by value for this to work?

Upvotes: 2

Views: 2795

Answers (1)

Kleist
Kleist

Reputation: 7985

You can make it copyable by deriving from matlab.mixin.CopyableClass, see the link for details.

Upvotes: 4

Related Questions