フィルターのクリア

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

6 ビュー (過去 30 日間)
Matthew Fall
Matthew Fall 2022 年 12 月 13 日
回答済み: Matthew Fall 2022 年 12 月 13 日
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

採用された回答

Matthew Fall
Matthew Fall 2022 年 12 月 13 日
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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by