필터 지우기
필터 지우기

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 CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by