Automatic deep copy of handle inside class object.

6 views (last 30 days)
SK
SK on 28 Sep 2014
Edited: SK on 28 Sep 2014
Is there any way in Matlab to have automatic deep copy of a handle object that is contained inside a class? Occassionally, class methods return values that are a result of a long calculation. It may be inconvenient for the caller to store them and pass them around. It is more convenient to pass the class object instead. I don't want to write:
Obj = Obj.CalculateSomething(...)
which can be inconvenient. Also the function name does not suggest that it is a modifier. I would rather have the class silently cache the calculated values. So I want to have a cache object. For example:
classdef Cache < handle
properties
Data;
end
methods
function this = Cache(varargin)
assert(iscellstr(varargin), 'Cache: Inputs must be valid variable names. ');
numfields = numel(varargin);
vals = cell(numfields, 1);
this.Data = cell2struct(vals, varargin(:), 1);
end
function val = Get(this, fname)
val = this.Data.(fname);
end
function Set(this, fname, val)
this.Data.(fname) = val;
end
end
end
Then if I want to cache data inside a class, say DataCruncher, I would write:
classdef DataCruncher
properties (Access = 'private')
h_cache;
% ... other properties ...
end
methods:
function PreciousVals = BigWork(dcobj)
PreciousVals = dcobj.h_cache.Get('Vals')
if isempty(PreciousVals)
% ... Big work ...
dcobj.h_cache.Set('Vals', PreciousVals);
end
end
end
end
Of course the cache is shared by any copies of DataCruncher objects. However it works fine as long as a new Cache object handle is created in any class method that modifies DataCruncher in a way that affects the BigWork() calculation.
But sometimes things get complicated, so I want the h_cache to be deep copied automatically whenever DataCruncher is copied.
Is there any way at all to do this in Matlab? Can Matlab.mixin.Copyable help?
Thank you.

Answers (0)

Categories

Find more on Construct and Work with Object Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!