matlablistenerdestructorhandlevalue-class

Executing destructor for a value class object in Matlab


I need to control destruction of a value-class object in Matlab. The problem is as following.

I have a some program (let's call it MyProg) that during execution creates a value-class object (lets call it MyValClass). MyValClass has a handle-class object as one of its properties (lets call it MyHandClass). That handle class initiates some events that MyProg listens to.

The problem appears is MyValClass object is destroyed (usually it happens on exceptions or user termination). I guess, that because there are still listeners listening to events of MyHandClass, the MyHandClass object is not destroyed, and remains in memory.

I would like to control the destruction of MyValClass object, so that I could implicitly delete its MyHandClass property. Is it possible?


Solution

  • Here is a bit of background on handle vs value classes:

    1. Objects of a value class are not "destroyed", and they do not have a destructor method. Think of value classes as behaving like the variable a when you've set a = 1. a is not "destroyed" when you type clear a, there's just no variable a any more. Value objects are just data, like 1, and they don't get destroyed.

    2. The above is true even if the value class has a method called delete. A delete method on a value class is just like any other method. It is not a destructor, and it does not get automatically called when the variable is cleared. It only gets called when you explicitly call it.

    3. Handle classes always, whether you implement one or not, have a method called delete, which is a destructor method (i.e. is called when the object is destroyed). If you don't implement one, they will be given a default method called delete, which does nothing other than destroy the object. If you implement a delete method, MATLAB will run that when destroying the object. But there is always a delete method that is a destructor, even if you don't implement one.

    So - to your question - if you wish to control the destruction of MyValClass, you must change it to become a handle class. If it's a value class, it is not destroyed and there's nothing to control.

    There are other things you might be able to do instead of directly "controlling the destruction". For example, you create an onCleanup object. This is a class that does nothing but execute a user-specified function on its destruction (it's a handle class, so it can do this). So if your code exits because of an exception or user termination, the onCleanup destructor will execute. You could, for example, put some code in there that would explicitly find references to MyHandlClass and deleted them.

    Hope that helps!