【发布时间】:2012-03-04 23:24:19
【问题描述】:
我有两个班级,Plant 和 Generator。 Generator 创建一个向量并通过notify() 广播它,Plant 监听它。类定义如下。请注意,我没有包含实际的数据生成方法,因为它与我的问题无关。
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
我注意到Generator 析构函数的行为非常奇怪:我第一次创建然后删除Generator 实例时,它直到我第二次创建Generator 实例时才运行析构函数。这是一个例子:
>> 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 CALLED??
>> 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?
我的析构函数每次都运行非常重要。这里发生了什么,我怎样才能让析构函数正常运行? (如果这不起作用,我可能会完全删除侦听器并直接从 Generator 实例中调用 Plant.ListenerCallback()。)
编辑:看起来当我执行 clear G 时,变量 G 已从工作区中删除 - 但 Generator 对象仍然存在于 P.Listener.Source 中。这就是为什么不调用析构函数的原因。所以我想没有办法通过删除G 来摆脱P.Listener .. 有没有办法让它做我想做的事情还是我只是卡住了?
【问题讨论】:
-
只尝试
delete G; clear G而不是clear G?从文档中,“您可以清除图形或其他对象的句柄,但这不会删除对象本身。使用 delete 删除对象和文件。删除对象不会删除用于存储其的变量(如果有)句柄。” -
@tmpearce - 确实有效。我希望只使用
clear G,因为这段代码是更大代码库的一部分。与我一起工作的大多数使用 MATLAB 的人都不知道delete和clear之间的区别,所以这可能会让人非常困惑。 -
是的,我明白了。您可能希望使用此信息更新您的问题,因为这不是析构函数的问题,而是对象上的
clear。 -
另外,请查看上一个问题了解更多信息:stackoverflow.com/questions/7236649/…
-
@strictlyrude27:请参阅下面我编辑的答案。简短回答:facepalm
标签: oop matlab destructor handle