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

21 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Guillaume
Guillaume il 15 Feb 2016
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

Più risposte (0)

Categorie

Scopri di più su Handle Classes in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by