Object destructor not running when listeners are involved
Show older comments
I have two classes, Plant and Generator. Generator creates a vector and broadcasts it via notify(), which Plant listens for. The classdefs are below. Note that I didn't include the actual data-generation method because it's irrelevent to my question.
classdef Plant < handle
properties
Listener
end
methods
function ListenerCallback(obj, data)
% Perform an operation on data
end
end
end
classdef Generator < handle
properties
plant
end
events
newSignal
end
methods
function obj = Generator(plant)
obj.plant = plant;
obj.plant.Listener = addlistener(obj, 'newSignal', ...
@(src, data) obj.plant.ListenerCallback(data));
end
function delete(obj)
delete(obj.plant.Listener);
disp('Generator instance deleted');
end
end
end
I noticed that the Generator destructor behaves really oddly: the first time I create then delete a Generator instance, it does not run the destructor until the second time I create the Generator instance. Here's an example:
>> P = Plant
P =
Plant handle
Properties:
Listener: []
Methods, Events, Superclasses
>> G = Generator(P)
G =
Generator handle
Properties:
plant: [1x1 Plant]
Methods, Events, Superclasses
>> clear G % DESTRUCTOR NOT DELETED??
>> G = Generator(P)
Generator instance deleted % why is the destructor run now?
G =
Generator handle
Properties:
plant: [1x1 Plant]
Methods, Events, Superclasses
>> clear G
Generator instance deleted % and why is the destructor run properly now?
It's pretty important that my destructor runs every time. What is going on here, and how can I get the destructor to operate properly? (I might just remove the listener altogether and directly call Plant.ListenerCallback() from the Generator instance if this doesn't work out.)
Accepted Answer
More Answers (0)
Categories
Find more on Graphics Object Properties in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!