Object cloning and copying

Distinguishes assignment by reference, shallow copy, and deep copy; Go and Rust express the same ideas with value semantics and explicit cloning.

C C23

C23
#include <stdio.h>

typedef struct {
    const char *tags[8];
    int count;
} Inner;

typedef struct {
    Inner *inner;
} Box;

int main(void) {
    Inner inner = { { "book" }, 1 };
    Box a = { &inner };

    Box b = a; // assignment copies the pointer: b.inner and a.inner are the same object (reference semantics)
    b.inner->tags[b.inner->count++] = "pen";
    printf("%d\n", a.inner->count); // 2: changes are visible through both

    Box c = a; // clone is equivalent to struct assignment: a new Box, but the inner pointer is still shared (shallow copy)
    c.inner->tags[c.inner->count++] = "paper";
    printf("%d %d", a.inner->count, c.inner->count); // 3 3: inner object shared
    return 0;
}
Output
2
3 3

C++ C++26

C++26
#include <iostream>
#include <string>
#include <vector>
struct Inner {
    std::vector<std::string> tags = {"book"};
};
struct Box {
    Inner* inner; // raw pointer member: copying copies only the pointer
};
int main() {
    Box a{new Inner()};
    Box b = a; // default copy (shallow copy): pointer copied by value, pointing to the same Inner
    b.inner->tags.push_back("pen");
    std::cout << a.inner->tags.size() << "\n"; // 2: changes are visible through both
    Box c = a; // copy constructor: also shallow
    c.inner->tags.push_back("paper");
    std::cout << a.inner->tags.size() << " " << c.inner->tags.size() << "\n"; // 3 3: inner shared
    delete a.inner; // all three share one object; it is freed only once (or managed by a smart pointer)
    return 0;
}
Output
2
3 3

C# v11.0.100

v11.0.100
var a = new Box();
a.Items.Add("book");
var b = a; // reference assignment: same object
b.Items.Add("pen");
Console.WriteLine(a.Items.Count); // 2: changes are visible through both
var c = a.ShallowCopy(); // clone (shallow copy)
c.Items.Add("paper");
Console.WriteLine($"{a.Items.Count} {c.Items.Count}"); // 3 3: inner list shared
// deep copy must be done manually: new Box { Items = new List<string>(a.Items) } or serialization

class Box {
    public List<string> Items = new();
    public Box ShallowCopy() => (Box)MemberwiseClone(); // shallow copy: inner list shared
}
Output
2
3 3

Go v1.27.4

v1.27.4
package main

import "fmt"

type Box struct {
    Items []string
}

func main() {
    a := Box{Items: []string{"book"}}
    b := a // struct assignment is a value copy
    b.Items = append(b.Items, "pen") // new slice, does not affect a
    fmt.Println(len(a.Items), len(b.Items))

    p := &a // pointer: same object shared
    p.Items = append(p.Items, "paper")
    fmt.Println(len(a.Items))
}
Output
1 2
2

Java v27.0.1

v27.0.1
import java.util.ArrayList;
import java.util.List;

public class Main {
    static class Box {
        List<String> items;
        Box(List<String> items) { this.items = items; }
        Box(Box other) { // copy constructor: conventional idiom
            this.items = new ArrayList<>(other.items);
        }
    }
    public static void main(String[] args) {
        Box a = new Box(new ArrayList<>(List.of("book")));
        Box b = new Box(a); // new object; the inner list is copied too
        b.items.add("pen");
        System.out.println(a.items.size() + " " + b.items.size());
        Box c = a; // object assignment is just a reference
        c.items.add("paper");
        System.out.println(a.items.size());
    }
}
Output
1 2
2

JavaScript v26.13.1

v26.13.1
const a = { items: ["book"] };
const b = a; // reference assignment: same object
b.items.push("pen");
console.log(a.items.length); // 2: changes are visible through both

const c = { ...a }; // shallow copy: copies only the first level
c.items.push("paper"); // inner array still shared
console.log(a.items.length, c.items.length); // 3 3

const d = structuredClone(a); // deep copy (modern API)
d.items.push("ink");
console.log(a.items.length, d.items.length); // 3 4
Output
2
3 3
3 4

PHP v8.6.0

v8.6.0
class Inner {
    public array $tags = ["book"];
}
class Box {
    public function __construct(public Inner $inner) {}
}
$a = new Box(new Inner());
$b = $a; // object assignment is just a reference: same object
$b->inner->tags[] = "pen";
echo count($a->inner->tags), "\n"; // 2: changes are visible through both
$c = clone $a; // clone: new object (shallow copy); the inner property still points to the same Inner instance
$c->inner->tags[] = "paper";
echo count($a->inner->tags), " ", count($c->inner->tags); // 3 3: inner object shared
// for a deep copy, implement __clone() to clone the inner object manually
Output
2
3 3

Python v3.15.2

v3.15.2
import copy

class Box:
    def __init__(self, items):
        self.items = items

a = Box(["book"])
b = a # reference: same object
b.items.append("pen")
print(len(a.items)) # 2: changes are visible through both
c = copy.copy(a) # shallow copy: new object, inner list still shared
c.items.append("paper") # the change lands on the shared list, visible to a as well
print(len(a.items), len(c.items)) # 3 3
d = copy.deepcopy(a) # deep copy: inner is copied too
d.items.append("ink") # affects only d's own list
print(len(a.items), len(d.items)) # 3 4
Output
2
3 3
3 4

Rust v1.99.1

v1.99.1
#[derive(Clone)] // derive the Clone trait to get clone()
struct Box_ {
    items: Vec<String>,
}

fn main() {
    let a = Box_ { items: vec![String::from("book")] };
    let mut b = a.clone(); // explicit deep copy (Vec contents copied too)
    b.items.push(String::from("pen"));
    println!("{} {}", a.items.len(), b.items.len());
    // let c = a; is move semantics by default: ownership moves and a can no longer be used,
    // copying requires an explicit clone() call
}
Output
1 2

TypeScript v26.13.1

v26.13.1
const a: { items: string[] } = { items: ["book"] };
const b = a; // reference assignment: same object
b.items.push("pen");
console.log(a.items.length); // 2: changes are visible through both

const c = { ...a }; // shallow copy: copies only the first level
c.items.push("paper"); // inner array still shared
console.log(a.items.length, c.items.length); // 3 3

const d = structuredClone(a); // deep copy
d.items.push("ink");
console.log(a.items.length, d.items.length); // 3 4
Output
2
3 3
3 4

Language differences

C: no classes — the example uses structs and pointers; assigning a struct copies it, but pointer members still share the pointee (shallow copy, same semantics as PHP clone).

C++: default copying is shallow — pointer members share the pointee; the heap object is freed once with a manual delete.

Go: struct assignment is a value copy (note that inner slices still share the backing array; call make again for independence), and only pointers share.

Java: assigning object variables is by reference (the example shows mutations visible through both); the convention is a copy constructor.

JavaScript: object variables assign by reference; shallow copy via object spread {...obj}; deep copy via structuredClone.

PHP: references vs. copies — object variables assign by reference (the example shows mutations visible through both); shallow copy via clone (shallow by default; implement __clone() for a deep copy), and deep copy requires implementing __clone() yourself.

Python: object variables assign by reference; shallow copy copy.copy; deep copy copy.deepcopy.

Rust: move semantics by default — getting a copy requires an explicit clone() (derive Clone), so copying is explicit, not implicit.