浅复制的不同类型 [已解决:别名 vs 复制]

huangapple go评论67阅读模式
英文:

Different types of Shallow copy [SOLVED: aliasing vs copying]

问题

这个问题不是关于解释浅工作和深工作的,而是关于浅拷贝示例的问题。

我正在做笔记,我想知道这两个示例是否都属于浅拷贝的范畴。是的,它们有一些不同,但它们都被称为“浅拷贝”吗?代码:

ArrayList<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Blue");

ArrayList<String> shallowOne = new ArrayList<>(colors);
ArrayList<String> shallowTwo = colors;

shallowOne 对象引用了 colors 对象内部的元素。

shallowTwo 直接引用了 colors 对象本身。

那么,它们都使用了著名的浅拷贝概念吗?还是说术语对它们有不同的含义?

英文:

This question is not about explaining how shallow/deep work, but examples of shallow copy.

I am making notes, and I wonder if these two examples both 'fall under the roof' of shallow copies. Yes, they are a little different, but are they both so called 'shallow copies'? Code:

ArrayList&lt;String&gt; colors = new ArrayList&lt;&gt;();
colors.add(&quot;Red&quot;);
colors.add(&quot;Blue&quot;);

ArrayList&lt;String&gt; shallowOne = new ArrayList&lt;&gt;(colors);
ArrayList&lt;String&gt; shallowTwo = colors;

ShallowOne has reference to elements inside object colors.

ShallowTwo has direct reference to object colors.

So, are they both using famous concept of Shallow copy? Or..terminology is different for them?

答案1

得分: 1

第二个你提供的例子并不是浅拷贝的示例。实际上,并没有发生任何拷贝:这被称为别名引用。

然而,在某些语言中,情况未必如此。比如在 Rust 中,如果数据类型被标记为 Copy,则在赋值时会进行浅拷贝或深拷贝,否则将进行移动赋值(旧名称不再可用,因此这里也不会发生别名引用)。

英文:

The second example you've given is not an example of shallow copying. In fact, no copy has occurred: this is called aliasing.

There are some languages, however, where this isn't necessarily true. In Rust, for instance, a shallow/deep copy is made on assignment if the datatype has been marked as Copy, and a move assignment happens otherwise (where the old name is no longer usable, so no aliasing happens here either).

huangapple
  • 本文由 发表于 2020年7月26日 21:24:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/63100735.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定