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
  1 件のコメント
Alek Xu
Alek Xu 2022 年 6 月 23 日
This seems to limit copy behavior for all other classes.

サインインしてコメントする。

その他の回答 (0 件)

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by