Ho to copy an object (deep copy) which has inside another object

조회 수: 11 (최근 30일)
Armindo
Armindo 2016년 2월 15일
댓글: Alek Xu 2022년 6월 23일
Hi,
I have an object (obj1) with the following properties:
PipeName
PipeVault
UnLock
Units
However the PipeVault is also an object (obj2) with the properties:
Name;
Value;
When I make a copy (deep copy) of the object (obj1) I get: obj1Copy and if I change one property like (obj1.PipeName) this change only affect the obj1.PipeName but not the obj1Copy.PipeName which is fine and is what I need. However if I change the property (obj1.PipeVault. Name) the obj1Copy.PipeVault. Name also change. Both classes (of obj1 and obj2) employ the matlab.mixin.Copyable. Therefore I expected the same behavior as for the obj1.PipeName. How can I make a deep copy of obj1 and I get a totally independent object obj2 ( that is if I change obj1.PipeVault. Name this would not change obj2.PipeVault. Name)
Kind regards,
Armindo

채택된 답변

Guillaume
Guillaume 2016년 2월 15일
As per its documentation matlab.mixin.Copyable does not make a deep copy of the object properties even if they themselves derived from copyable: "In making a shallow copy, MATLAB® does not call copy recursively on any handles contained in property values." You actually have to override the copyElement to make the copy yourself:
classdef Pipe < matlab.mixin.Copyable
properties
PipeName;
PipeVault;
UnLock;
Units;
end
methods (Access = protected)
function thiscopy = copyElement(this)
thiscopy = copyElement@matlab.mixin.Copyable(this); %shallow copy of all elements
thiscopy.PipeVault = copy(this.PipeVault); %Deep copy of pipevault
end
end
end

추가 답변 (0개)

태그

Community Treasure Hunt

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

Start Hunting!

Translated by