Azzera filtri
Azzera filtri

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

6 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Matthew Fall
Matthew Fall il 13 Dic 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

Più risposte (0)

Categorie

Scopri di più su MATLAB in Help Center e File Exchange

Prodotti


Release

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by