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

23 vues (au cours des 30 derniers jours)
Armindo
Armindo le 15 Fév 2016
Commenté : Alek Xu le 23 Juin 2022
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

Réponse acceptée

Guillaume
Guillaume le 15 Fév 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
  1 commentaire
Alek Xu
Alek Xu le 23 Juin 2022
This seems to limit copy behavior for all other classes.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Handle Classes dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by