The matlab.mixin.Copyable page describes the following information:
The copy method makes a shallow copy of the object.
copyElementis a Protected Method that the copy method uses to perform the copy operation on each object in the input arrayMATLAB® does not call copy recursively on any handles contained in property values.
The copy method copies data without calling the class constructor or property set functions. It therefore produces no side effects.
There is four questions:
The
copymethod makes a shallow copy of the object. But in overloadcopyElementcode usecopyto make a deep copy of theDeepCpobject (this page). Why?So, can the copy method perform deep copying ? Or notmethods(Access = protected) % Override copyElement method: function cpObj = copyElement(obj) % Make a shallow copy of all four properties cpObj = [email protected](obj); % Make a deep copy of the DeepCp object cpObj.DeepObj = copy(obj.DeepObj); end endBy running the following code, you will notice that as long as it's an object of the
matlab.mixin.Copyableclass, using copy will achieve deep copying. Therefore, is it not an incorrect conclusion to say, "The copy method makes a shallow copy of the object"?classdef DeepCp < matlab.mixin.Copyable properties DpProp end methods function obj = DeepCp(val) obj.DpProp=val; end end endRun the following command in the command line:
A=DeepCp(7); B=copy(A); A.DpProp=222; BcopyElementis a Protected Method. So, is it necessary to declareAccess = protectedwhen overloadingcopyElement? Is it always required to do so? Do you have to redeclare all method attributes when overloading built-in methods in MATLAB?"copyElement is a protected method that the copy method uses to perform the copy operation on each object in the input array"
Since 'copyElement' ultimately performs the copying work, why does referencing the parent class's 'copyElement' result in a shallow copy, while using 'copy' directly results in a deep copy? Does using 'copy' directly not ultimately invoke 'copyElement' as well?
% Make a shallow copy of all four properties cpObj = [email protected](obj); % Make a deep copy of the DeepCp object cpObj.DeepObj = copy(obj.DeepObj);
MATLAB® does not call copy recursively on any handles contained in property values. Since the copy method is sealed, it cannot be overloaded or defined. So how can a situation with recursive calls to copy occur? For instance, in the case of get methods, when you define a get method within a class, it may reference the class's properties, creating a possibility of recursive calls to the get method. Therefore, it is explicitly stated that there should not be a recursive call situation in get methods.
The copy method copies data without calling the class constructor or property set functions. It therefore produces no side effects. What built-in methods call "the class constructor or property set functions"? What are the side effects of calling the class constructor or property set functions?