cannot update class definition in Matlab

后端 未结 2 983
温柔的废话
温柔的废话 2021-01-06 09:31

I am running into an infuriating problem with Matlab, and an earlier answer to apparently the same problem didn\'t help me, unfortunately. I apologize that the question is

相关标签:
2条回答
  • 2021-01-06 10:10

    You have an intermediate instance myClass.father that is not being destroyed by MATLAB. You have to deleteit yourself

    >> clear grandpa
    >> delete(son.precursors{1})
    >> clear son
    >> clear classes
    >> son = myClass.son
    son = 
        son    
    >> sumVal(son)
    ans =
         6
    

    Edit: Alternatively, you can add a destructor to your class

        function delete(obj)
            if isa(obj.precursors{1}, 'myClass')
                delete(obj.precursors{1});
            end
        end
    

    and use delete(son) instead of leaving it to clear function to destroy. You can extend this to your case and recursively delete all instances in your tree.

    0 讨论(0)
  • 2021-01-06 10:11

    Those instances are "hiding" in the myClass enumeration class itself. Matlab is storing a reference to each of those named instances so when you reference them like myClass.father you get the same object back, instead of it constructing a new one. Probably similar to how values are stored in Constant properties on classes.

    If you have any other classes that refer to the myClass.xxx enumerated instances in Constant properties, enumerations, or persistent variables, they could also be holding on to references to them.

    Try doing clear classes a few times in a row instead of just once.

    To help debug this, you could put a couple debugging printf() statements in the constructor and destructor for this class, so you can see when the instances are really created and cleaned up.

      function obj = myClass(pre, num, val)
          % constructor
          if nargin > 0
              obj.precursors = pre;
              obj.numPre = num;
              obj.value = val;
          end
          printf('myClass: created (%d, %d, nargin=%d)\n', obj.numPre, obj.value, nargin);
      end
      function delete(obj)
          printf('myClass: deleting (%d, %d)\n', obj.numPre, obj.value);
      end
    
    0 讨论(0)
提交回复
热议问题