Filter löschen
Filter löschen

Why can't we define destructors for non-handle classes?

6 Ansichten (letzte 30 Tage)
Matthew Fall
Matthew Fall am 13 Dez. 2022
Beantwortet: Matthew Fall am 13 Dez. 2022
I looked up documentation for destructors in Matlab, but it seems like they can only be defined for handle classes. Why is that? I can easily think of a use case for a non-handle class that needs a destructor:
classdef FileReader
% FileReader very simple file reader
properties
fid
end
methods
function obj = FileReader(file)
obj.fid = fopen(file, 'r');
end
function varargout = read(obj,varargin)
[varargout{1:nargout}] = obj.fread(obj.fid, varargin{:});
end
function delete(obj)
fclose(obj.fid);
end
end
end

Akzeptierte Antwort

Matthew Fall
Matthew Fall am 13 Dez. 2022
Never mind, I figured out how to do this with onCleanup:
classdef FileReader
% FileReader very simple file reader
properties
fid
end
properties(Access=protected)
cleanup
end
methods
function obj = FileReader(file)
obj.fid = fopen(file, 'r');
obj.cleanup = onCleanup(@() obj.delete);
end
function varargout = read(obj,varargin)
[varargout{1:nargout}] = fread(obj.fid, varargin{:});
end
function delete(obj)
fclose(obj.fid);
disp('file closed!')
end
end
end

Weitere Antworten (0)

Kategorien

Mehr zu MATLAB finden Sie in Help Center und File Exchange

Produkte


Version

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by