Effacer les filtres
Effacer les filtres

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

6 vues (au cours des 30 derniers jours)
Matthew Fall
Matthew Fall le 13 Déc 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

Réponse acceptée

Matthew Fall
Matthew Fall le 13 Déc 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

Plus de réponses (0)

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Produits


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by