Conceptcore
Object cloning
Also called shallow copy, deep copy, copy constructor, Clone trait, Cloneable, deepcopy, structuredClone, MemberwiseClone, object copying.
Object cloning makes a new object with the same state as an existing one. A shallow copy shares the objects that the fields refer to, and a deep copy copies them too.
- Applies to
- core-languages
Idea
An object often holds references to other objects: a team holds a list of members, and a document holds a list of pages. To copy such an object, a program must choose what to do with the objects that the fields refer to. There are three levels:
- A new reference. Assignment in Python, Java, JavaScript and C# copies only the reference, so both names refer to one object. In Python, "Assignment statements in Python do not copy objects, they create bindings between a target and an object."1
- A shallow copy. A new object gets the same field values. Its fields refer to the same inner objects as the original. MDN: "A shallow copy of an object is a copy whose properties share the same references (point to the same underlying values) as those of the source object from which the copy was made."2
- A deep copy. A new object gets copies of the inner objects too, at each level. MDN: "A deep copy of an object is a copy whose properties do not share the same references (point to the same underlying values) as those of the source object from which the copy was made."3
The difference matters only for an object that refers to mutable objects. For a value that has only numbers and strings, or only immutable parts, a shallow copy and a deep copy behave the same.
How it works
Python's copy module has both copies. A shallow copy "constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original", and a deep copy "constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original".1 A list of lists shows the three levels:
import copy
grid = [[1, 2], [3, 4]]
alias = grid
shallow = copy.copy(grid)
deep = copy.deepcopy(grid)
grid[0][0] = 99
grid.append([5, 6])
print(alias)
print(shallow)
print(deep)
[[99, 2], [3, 4], [5, 6]]
[[99, 2], [3, 4]]
[[1, 2], [3, 4]]
The alias sees both changes, because it is the same list. The shallow copy is a new outer list, so it does not get the new row, but its rows are the rows of grid, so it sees the change to grid[0]. The deep copy shares nothing.
A deep copy must walk a graph, not a tree. Python names the two problems: "Recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop", and "Because deep copy copies everything it may copy too much, such as data which is intended to be shared between copies."1 deepcopy keeps a memo of the objects that it copied, so an object that appears twice is copied once and a cycle ends. A class can control its copies with __copy__ and __deepcopy__.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Native | |
| Java | Native | |
| C | Idiom | Assignment copies a struct member by member, and a pointer member copies only the address; a program writes a function that copies the data that the pointers point to. |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | As JavaScript; spread syntax copies shallowly and structuredClone copies deeply; no example file because it would repeat the JavaScript answer. |
| Go | Idiom | |
| Rust | Standard library | |
| Kotlin | Native | A data class has copy(), which makes a shallow copy and can change some properties; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Does not apply | SQL has no objects; INSERT ... SELECT copies rows into a table. |
| Bash | Does not apply | Variables hold strings; an array is copied with b=("${a[@]}"), and there are no objects with references. |
| PowerShell | Native | PowerShell objects are .NET objects, so the .NET rules apply; Clone() on an array or a hash table copies one level. |
| HTML | Does not apply | HTML has no objects; the DOM method cloneNode copies an element in a script. |
| CSS | Does not apply | CSS has no objects to copy. |
| Regular expressions | Does not apply | Regular expressions have no objects. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | stdlib | copy.copy and copy.deepcopy; __copy__ and __deepcopy__ |
| JavaScript | native | spread syntax and Object.assign copy shallowly; structuredClone copies deeply |
| TypeScript | native | as JavaScript |
| Java | native | Object.clone with Cloneable, shallow by default; copy constructors |
| Kotlin | native | copy() of a data class, shallow |
| C# | native | MemberwiseClone, shallow; ICloneable; with on records |
| Go | idiom | assignment copies a struct; slices.Clone and maps.Clone copy one level |
| Rust | stdlib | trait Clone, explicit and usually deep; trait Copy for bitwise copies |
| C | idiom | assignment copies a struct; a function copies what the pointers point to |
| C++ | native | copy constructor and copy assignment, member-wise by default |
| Bash | n/a | variables hold strings; b=("${a[@]}") copies an array |
| PowerShell | native | .NET objects; Clone() on arrays and hash tables copies one level |
| SQL | n/a | no objects; INSERT ... SELECT copies rows |
| Regex | n/a | no objects |
| HTML | n/a | no objects; the DOM method cloneNode copies an element |
| CSS | n/a | no objects |
- Java puts
cloneonObjectas a protected method. It makes a field-for-field copy, which "performs a "shallow copy" of this object, not a "deep copy" operation".4 A class must implementCloneable, orclonethrowsCloneNotSupportedException, but "this interface does not contain the clone method".5 - C# has the protected
MemberwiseClone: "If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object."6 The interfaceICloneable"does not specify whether the cloning operation performs a deep copy, a shallow copy, or something in between".7 - Rust makes copies explicit.
Cloneis "A common trait that allows explicit creation of a duplicate value", and#[derive(Clone)]clones each field, so aVecfield becomes a new vector.8Copyis for "Types whose values can be duplicated simply by copying bits"; other types move on assignment.9 - C++ calls the copy constructor for
T b = a;. The implicit one "performs full member-wise copy of the object's direct base class subobjects and member subobjects".10 Astd::vectormember copies its elements, so the copy is deep for values; a raw pointer or astd::shared_ptrmember copies only the pointer. - Go copies a struct on assignment, field by field. A slice field shares its array: "A slice therefore shares storage with its array and with other slices of the same array".11
slices.Clonemakes a new array, but "The elements are copied using assignment, so this is a shallow clone."12 - JavaScript spread syntax
{ ...obj }is a shallow copy; "all standard built-in object-copy operations (spread syntax, Array.prototype.concat(), Array.prototype.slice(), Array.from(), and Object.assign()) create shallow copies".2structuredClonemakes a deep copy of plain data, but "The prototype chain is not walked or duplicated."13 - Kotlin data classes have
copy(), which can change some properties; "The copy() function creates a shallow copy of the instance."14
import copy
class Team:
def __init__(self, name, members):
self.name = name
self.members = members
def __deepcopy__(self, memo):
# The name is an immutable string, so only the list needs a copy.
return Team(self.name, copy.deepcopy(self.members, memo))
a = Team("red", ["Ann", "Bo"])
shallow = copy.copy(a)
deep = copy.deepcopy(a)
a.members.append("Cy")
shallow.name = "blue"
print(a.name, a.members)
print(shallow.name, shallow.members)
print(deep.name, deep.members)
print(shallow.members is a.members, deep.members is a.members)
red ['Ann', 'Bo', 'Cy']
blue ['Ann', 'Bo', 'Cy']
red ['Ann', 'Bo']
True False
- Verdict: stdlib.
copy.copymakes a shallow copy andcopy.deepcopymakes a deep copy of any object, without code in the class. - The shallow copy has its own
name, so the new name does not changea, but it shares thememberslist witha. __deepcopy__is optional; here it shows how a class controls its deep copy. It passesmemoon, so shared objects and cycles are copied once.
#include <iostream>
#include <memory>
#include <string>
#include <vector>
struct Team {
std::string name;
std::vector<std::string> members;
};
struct SharedTeam {
std::shared_ptr<std::vector<std::string>> members;
};
void print(const std::vector<std::string>& v) {
for (const auto& s : v) std::cout << s << ' ';
std::cout << '\n';
}
int main() {
Team a{"red", {"Ann", "Bo"}};
Team b = a; // the implicit copy constructor copies each member
b.members.push_back("Cy");
print(a.members);
print(b.members);
SharedTeam s{std::make_shared<std::vector<std::string>>(
std::vector<std::string>{"Ann"})};
SharedTeam t = s; // copies the pointer, not the vector
t.members->push_back("Cy");
print(*s.members);
std::cout << s.members.use_count() << '\n';
}
Ann Bo
Ann Bo Cy
Ann Cy
2
- Verdict: native.
Team b = a;calls the copy constructor, which the compiler writes when the class does not declare one. It copies each member with that member's own copy constructor. std::vectorandstd::stringcopy their elements, so the copy ofTeamis deep.- A
std::shared_ptrmember copies the pointer and raises the use count; a raw pointer member copies only the address. Such a class needs its own copy constructor if the copy must own its data.
import java.util.ArrayList;
import java.util.List;
public class Main {
static final class Team implements Cloneable {
String name;
List<String> members;
Team(String name, List<String> members) {
this.name = name;
this.members = members;
}
// A copy constructor: it chooses a deep copy for the list.
Team(Team other) {
this(other.name, new ArrayList<>(other.members));
}
// Object.clone copies the fields; the list is shared.
@Override
public Team clone() {
try {
return (Team) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
}
public static void main(String[] args) {
Team a = new Team("red", new ArrayList<>(List.of("Ann", "Bo")));
Team shallow = a.clone();
Team deep = new Team(a);
a.members.add("Cy");
System.out.println(shallow.members);
System.out.println(deep.members);
System.out.println(shallow != a);
System.out.println(shallow.members == a.members);
}
}
[Ann, Bo, Cy]
[Ann, Bo]
true
true
- Verdict: native.
Object.cloneis protected; a class implementsCloneableand overridescloneas a public method that callssuper.clone(). super.clone()copies each field, so the clone is a new object with the same list.- The copy constructor is ordinary code, so it can copy the list. It needs no cast and no checked exception.
using System;
using System.Collections.Generic;
var a = new Team("red", new List<string> { "Ann", "Bo" });
var shallow = a.ShallowCopy();
var deep = a.DeepCopy();
a.Members.Add("Cy");
Console.WriteLine(string.Join(", ", shallow.Members));
Console.WriteLine(string.Join(", ", deep.Members));
Console.WriteLine(ReferenceEquals(shallow.Members, a.Members));
var p = new Player("Ann", new List<int> { 3 });
var q = p with { Name = "Bo" };
q.Scores.Add(5);
Console.WriteLine($"{p.Name} {p.Scores.Count}");
sealed class Team
{
public string Name;
public List<string> Members;
public Team(string name, List<string> members)
{
Name = name;
Members = members;
}
// MemberwiseClone copies each field; the list is shared.
public Team ShallowCopy() => (Team)MemberwiseClone();
public Team DeepCopy() => new Team(Name, new List<string>(Members));
}
record Player(string Name, List<int> Scores);
Ann, Bo, Cy
Ann, Bo
True
Ann 2
- Verdict: native.
Object.MemberwiseCloneis protected, so a class wraps it in a public method; the copy shares the objects that the fields refer to. - The deep copy is ordinary code that makes a new list.
- A
withexpression on a record is also a shallow copy:qhas a new name, but it shares the list of scores withp.
const team = { name: "red", members: ["Ann", "Bo"], made: new Date(0) };
const shallow = { ...team };
const deep = structuredClone(team);
team.members.push("Cy");
console.log(shallow.members);
console.log(deep.members);
console.log(deep.made instanceof Date, deep.made === team.made);
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
const p = structuredClone(new Point(1, 2));
console.log(p instanceof Point, p.x, p.y);
[ 'Ann', 'Bo', 'Cy' ]
[ 'Ann', 'Bo' ]
true false
false 1 2
- Verdict: native. Spread syntax copies the own properties of an object into a new object; the values are not copied, so the copy is shallow.
structuredClonecopies plain data deeply, and it knows built-in types such asDate,MapandSet.- It does not keep the class: the copy of a
Pointis a plain object with the fieldsxandy, so a class needs its own copy method.
package main
import (
"fmt"
"slices"
)
type Team struct {
Name string
Members []string
}
// DeepCopy gives the copy its own array of members.
func (t Team) DeepCopy() Team {
t.Members = slices.Clone(t.Members)
return t
}
func main() {
a := Team{Name: "red", Members: []string{"Ann", "Bo"}}
shallow := a
deep := a.DeepCopy()
a.Name = "blue"
a.Members[0] = "Zoe"
fmt.Println(shallow.Name, shallow.Members)
fmt.Println(deep.Name, deep.Members)
}
red [Zoe Bo]
red [Ann Bo]
- Verdict: idiom. Assignment copies a struct field by field, so
shallowhas its ownName. - A slice is a small header that points to an array. The copied header points to the same array, so a change of an element shows in both.
slices.Clonemakes a new array. The elements are copied by assignment, so a slice of slices or of pointers needs a loop for a deeper copy.
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Clone, Debug)]
struct Team {
name: String,
members: Vec<String>,
}
#[derive(Clone, Debug)]
struct SharedTeam {
members: Rc<RefCell<Vec<String>>>,
}
fn main() {
let a = Team {
name: "red".to_string(),
members: vec!["Ann".to_string(), "Bo".to_string()],
};
let mut b = a.clone();
b.members.push("Cy".to_string());
println!("{:?}", a.members);
println!("{:?}", b.members);
let s = SharedTeam {
members: Rc::new(RefCell::new(vec!["Ann".to_string()])),
};
let t = s.clone();
t.members.borrow_mut().push("Cy".to_string());
println!("{:?}", s.members.borrow());
println!("{}", Rc::strong_count(&s.members));
}
["Ann", "Bo"]
["Ann", "Bo", "Cy"]
["Ann", "Cy"]
2
- Verdict: stdlib.
#[derive(Clone)]callscloneon each field.StringandVecclone their data, so the clone ofTeamis deep. Rc::clonemakes a new pointer to the same data and adds 1 to the count, so the clone ofSharedTeamshares the list.- The copy is always visible in the code as a call to
clone. Assignmentlet b = a;moves the value, andacan no longer be used.
Variations and related ideas
- Copy constructors and factories.
new Team(other)orTeam.copyOf(other)is a normal method, so it can choose the depth for each field. - Copy with changes. Kotlin's
copy(age = 20), C#'swithexpression and Python'sdataclasses.replacemake a shallow copy and set some fields. They suit immutable types: see data classes. - Immutable objects. An object that never changes can be shared without a copy. A deep copy of an immutable value is a waste. See immutability.
- Lazy copy. A copy can share the data at first and copy it only when one side writes. Wikipedia calls this a lazy copy: "When initially copying an object, a (fast) shallow copy is used. A counter is also used to track how many objects share the data."15 This is copy-on-write.
- Move. Rust and C++ can move a value: the new owner takes the data, and the old name can no longer use it. A move costs as little as a shallow copy and avoids sharing.
Pitfalls
- A shallow copy where a deep copy was meant. The copy and the original share the inner objects, so a change through one shows in the other:
const team = { name: "red", members: ["Ann", "Bo"] };
const copy = { ...team };
copy.name = "blue";
copy.members.push("Cy");
console.log(team.name, team.members);
red [ 'Ann', 'Bo', 'Cy' ]
The new name stays in the copy, but the new member is in both, because both refer to one array.
- A deep copy of a shared resource. A deep copy of an object that holds a file, a connection, a cache or a parent link copies too much. Python does not copy "module, method, stack trace, stack frame, file, socket, window, or any similar types".1 Copy the data and share the resource, or write the copy method by hand.
- A derived clone of a shared pointer. In Rust,
#[derive(Clone)]on a struct that holds anRcor anArcclones the pointer, not the data: "the cloned struct will share mutable state with the original".8 The same is true for a C++shared_ptrmember. - A copy that loses the type.
structuredClonecopies the fields of an object but not its class, so the copy of a class instance is a plain object without the methods. Functions cannot be copied at all: "attempting to throws a DataCloneError exception".13 - A
clonecontract that is not checked. Java'scloneshould return an object that is "independent of this object (which is being cloned)", butsuper.clone()alone does not give that for a mutable field.4 The class must replace each such field with a copy.
Cost
A shallow copy costs time and memory in proportion to the number of fields of the top object. A deep copy costs time and memory in proportion to the number of objects that are reachable from it, which can be the whole data structure. A deep copy that handles shared objects and cycles, such as deepcopy with its memo, also uses a table of the copied objects. Cloning a large structure in a loop is a common hidden cost; share immutable parts, or use copy-on-write.
History
The terms come from Smalltalk-80: "The terminology of shallow copy and deep copy dates to Smalltalk-80."15 Its classes had the methods shallowCopy and deepCopy. Java put clone on Object with the marker interface Cloneable, and .NET added MemberwiseClone and ICloneable. Later designs made copies explicit and typed: Rust separates the cheap Copy from the explicit Clone, and records and data classes give a shallow copy with changes.
References
- copy, Shallow and deep copy operations, Python standard library, Introduction
- Shallow copy, MDN Glossary, Definition
- Deep copy, MDN Glossary, Definition
- Object (Java SE 21 & JDK 21), API documentation, clone
- Cloneable (Java SE 21 & JDK 21), API documentation, Description
- Object.MemberwiseClone Method, .NET API reference, Remarks
- ICloneable Interface, .NET API reference, Remarks
- Clone trait, Rust standard library, Description
- Copy trait, Rust standard library, Description; What's the difference between Copy and Clone?
- Copy constructors, cppreference.com, Introduction; Implicitly-defined copy constructor
- The Go Programming Language Specification, Slice types
- slices package, Go standard library, func Clone
- The structured clone algorithm, MDN, Things that don't work with structured clone
- Data classes, Kotlin documentation, Copying
- Object copying, Wikipedia, Methods of copying; Lazy copy
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag F4T2ZQ Edit this page History Report an error Markdown