我有兩個類,Plant
和Generator
。 Generator
創建一個矢量並通過notify()
播放它,其中Plant
監聽。下面的classdefs。請注意,我沒有包含實際的數據生成方法,因爲這與我的問題無關。MATLAB - 對象析構函數在涉及偵聽器時不運行
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?
這是我的析構函數運行每次是很重要的。這裏發生了什麼,我怎樣才能讓析構函數正常運行? (我可能只是刪除偵聽乾脆直接調用Plant.ListenerCallback()
從Generator
例如,如果這個不奏效。)
編輯:看起來,當我做clear G
,變量G
從工作區中刪除 - 但Generator
對象依然存在於P.Listener.Source
中。這就是爲什麼析構函數沒有被調用。所以我想沒有辦法擺脫P.Listener
刪除G
..有什麼辦法讓這個做我想做的或者我只是卡住了嗎?
嘗試'刪除G;清除G'而不是'只清除G'?從文檔中,「您可以清除圖形或其他對象的句柄,但不會刪除對象本身,使用delete刪除對象和文件。刪除對象不會刪除變量(如果有的話)用於存儲它處理。」 – tmpearce 2012-03-05 01:04:43
@tmpearce - 確實有效。我只希望使用'clear G',因爲這個代碼是一個更大的代碼庫的一部分。我使用MATLAB的大多數人都不知道'delete'和'clear'有什麼區別,所以這可能會讓人感到困惑。 – 2012-03-05 01:13:55
是的,我明白了。你可能想用這個信息來更新你的問題,因爲它不是析構函數的問題,而是對象上的'clear'。 – tmpearce 2012-03-05 01:25:32