Programming Search⌘K

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)
Output
[[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

LanguageVerdictNote
PythonStandard library
C++Native
JavaNative
CIdiomAssignment 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
JavaScriptNative
TypeScriptNativeAs JavaScript; spread syntax copies shallowly and structuredClone copies deeply; no example file because it would repeat the JavaScript answer.
GoIdiom
RustStandard library
KotlinNativeA 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.
SQLDoes not applySQL has no objects; INSERT ... SELECT copies rows into a table.
BashDoes not applyVariables hold strings; an array is copied with b=("${a[@]}"), and there are no objects with references.
PowerShellNativePowerShell objects are .NET objects, so the .NET rules apply; Clone() on an array or a hash table copies one level.
HTMLDoes not applyHTML has no objects; the DOM method cloneNode copies an element in a script.
CSSDoes not applyCSS has no objects to copy.
Regular expressionsDoes not applyRegular 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 clone on Object as 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 implement Cloneable, or clone throws CloneNotSupportedException, 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 interface ICloneable "does not specify whether the cloning operation performs a deep copy, a shallow copy, or something in between".7
  • Rust makes copies explicit. Clone is "A common trait that allows explicit creation of a duplicate value", and #[derive(Clone)] clones each field, so a Vec field becomes a new vector.8 Copy is 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 A std::vector member copies its elements, so the copy is deep for values; a raw pointer or a std::shared_ptr member 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.Clone makes 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".2 structuredClone makes 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
PythonGitHub
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)
Output
red ['Ann', 'Bo', 'Cy']
blue ['Ann', 'Bo', 'Cy']
red ['Ann', 'Bo']
True False
  • Verdict: stdlib. copy.copy makes a shallow copy and copy.deepcopy makes a deep copy of any object, without code in the class.
  • The shallow copy has its own name, so the new name does not change a, but it shares the members list with a.
  • __deepcopy__ is optional; here it shows how a class controls its deep copy. It passes memo on, 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';
}
Output
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::vector and std::string copy their elements, so the copy of Team is deep.
  • A std::shared_ptr member 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.
JavaGitHub
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);
    }
}
Output
[Ann, Bo, Cy]
[Ann, Bo]
true
true
  • Verdict: native. Object.clone is protected; a class implements Cloneable and overrides clone as a public method that calls super.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);
Output
Ann, Bo, Cy
Ann, Bo
True
Ann 2
  • Verdict: native. Object.MemberwiseClone is 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 with expression on a record is also a shallow copy: q has a new name, but it shares the list of scores with p.
JavaScriptGitHub
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);
Output
[ '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.
  • structuredClone copies plain data deeply, and it knows built-in types such as Date, Map and Set.
  • It does not keep the class: the copy of a Point is a plain object with the fields x and y, 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)
}
Output
red [Zoe Bo]
red [Ann Bo]
  • Verdict: idiom. Assignment copies a struct field by field, so shallow has its own Name.
  • 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.Clone makes a new array. The elements are copied by assignment, so a slice of slices or of pointers needs a loop for a deeper copy.
RustGitHub
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));
}
Output
["Ann", "Bo"]
["Ann", "Bo", "Cy"]
["Ann", "Cy"]
2
  • Verdict: stdlib. #[derive(Clone)] calls clone on each field. String and Vec clone their data, so the clone of Team is deep.
  • Rc::clone makes a new pointer to the same data and adds 1 to the count, so the clone of SharedTeam shares the list.
  • The copy is always visible in the code as a call to clone. Assignment let b = a; moves the value, and a can no longer be used.
  • Copy constructors and factories. new Team(other) or Team.copyOf(other) is a normal method, so it can choose the depth for each field.
  • Copy with changes. Kotlin's copy(age = 20), C#'s with expression and Python's dataclasses.replace make 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);
Output
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 an Rc or an Arc clones the pointer, not the data: "the cloned struct will share mutable state with the original".8 The same is true for a C++ shared_ptr member.
  • A copy that loses the type. structuredClone copies 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 clone contract that is not checked. Java's clone should return an object that is "independent of this object (which is being cloned)", but super.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

  1. copy, Shallow and deep copy operations, Python standard library, Introduction
  2. Shallow copy, MDN Glossary, Definition
  3. Deep copy, MDN Glossary, Definition
  4. Object (Java SE 21 & JDK 21), API documentation, clone
  5. Cloneable (Java SE 21 & JDK 21), API documentation, Description
  6. Object.MemberwiseClone Method, .NET API reference, Remarks
  7. ICloneable Interface, .NET API reference, Remarks
  8. Clone trait, Rust standard library, Description
  9. Copy trait, Rust standard library, Description; What's the difference between Copy and Clone?
  10. Copy constructors, cppreference.com, Introduction; Implicitly-defined copy constructor
  11. The Go Programming Language Specification, Slice types
  12. slices package, Go standard library, func Clone
  13. The structured clone algorithm, MDN, Things that don't work with structured clone
  14. Data classes, Kotlin documentation, Copying
  15. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/F4T2ZQ/text.yaml