Array Value Semantics and Copy-on-Write

What assignment actually does — PHP array value semantics and COW against array assignment in 10 languages.

C C23

C23
#include <stdio.h>
#include <string.h>

/* C arrays decay to pointers: assignment shares the same memory,
   so "copy" is a manual memcpy and pass-by-pointer mutates in place */
void push(int *arr, int *len, int v) { arr[(*len)++] = v; }

int main(void) {
    int a[4] = {1, 2, 3}; /* spare slot reserved for push() */
    int len = 3;
    int b[4];
    memcpy(b, a, sizeof a); /* explicit copy */
    b[3] = 4;
    printf("%d,%d,%d\n", a[0], a[1], a[2]);
    printf("%d,%d,%d,%d\n", b[0], b[1], b[2], b[3]);

    push(a, &len, 99);
    printf("%d,%d,%d,%d\n", a[0], a[1], a[2], a[3]);
    return 0;
}
Output
1,2,3
1,2,3,4
1,2,3,99

C++ C++26

C++26
#include <cstdio>
#include <vector>

// std::vector has value semantics: assignment eagerly copies, so writes
// to the copy never reach the original — no copy-on-write, no sharing
int main() {
    std::vector<int> a{1, 2, 3};
    std::vector<int> b = a;
    b.push_back(4);
    std::printf("%d,%d,%d\n", a[0], a[1], a[2]);
    std::printf("%d,%d,%d,%d\n", b[0], b[1], b[2], b[3]);
    a.push_back(99);
    std::printf("%d,%d,%d,%d\n", a[0], a[1], a[2], a[3]);
}
Output
1,2,3
1,2,3,4
1,2,3,99

C# v11.0.100

v11.0.100
var a = new List<int> { 1, 2, 3 };
var b = a;                // same reference: no copy happens
b.Add(4);
Console.WriteLine(string.Join(",", a)); // the append is visible through a
var c = new List<int>(a); // an explicit copy is exactly that: manual
c.Add(99);
Console.WriteLine(string.Join(",", a)); // a stays untouched
Console.WriteLine(string.Join(",", c));
Output
1,2,3,4
1,2,3,4
1,2,3,4,99

Go v1.27.4

v1.27.4
package main

import "fmt"

// slice assignment copies the header (pointer, len, cap), so both slices
// share one backing array until append has to reallocate
func main() {
	a := []int{1, 2, 3}
	b := a    // header copied, backing array shared
	b[0] = 99 // writes through to a
	fmt.Println(a[0], b[0])
	b = append(b, 4) // cap exceeded: b is reallocated and detaches
	b[0] = 7
	fmt.Println(a[0], b[0])
}
Output
99 99
99 7

Java v27.0.1

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

public class Main {
    public static void main(String[] args) {
        List<Integer> a = new ArrayList<>(List.of(1, 2, 3));
        List<Integer> b = a;  // same reference: no copy happens
        b.add(4);
        System.out.println(a); // the add is visible through a
        List<Integer> c = new ArrayList<>(a); // an explicit copy is manual
        c.add(99);
        System.out.println(a);
        System.out.println(c);
    }
}
Output
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4, 99]

JavaScript v26.13.1

v26.13.1
const a = [1, 2, 3];
const b = a;    // the same array: no copy happens
b.push(4);
console.log(a.join(",")); // the push is visible through a
const c = [...a];         // spread makes an explicit shallow copy
c.push(99);
console.log(a.join(",")); // a stays untouched
console.log(c.join(","));
Output
1,2,3,4
1,2,3,4
1,2,3,4,99

PHP v8.6.0

v8.6.0
// PHP arrays have value semantics: assignment behaves as a full copy.
// Under the hood the engine shares the storage and splits it only when
// one side writes (copy-on-write) — the semantics never leak the trick
$a = [1, 2, 3];
$b = $a;       // semantic copy; physical storage still shared
$b[] = 4;      // write: the arrays split here

echo implode(",", $a), "\n";

echo implode(",", $b), "\n";

// pass-by-reference (&$) is the explicit exception: it skips the copy
// and hands the function the caller's own array
function push(&$arr, $v) { $arr[] = $v; }
push($a, 99);
echo implode(",", $a), "\n";
Output
1,2,3
1,2,3,4
1,2,3,99

Python v3.15.2

v3.15.2
a = [1, 2, 3]
b = a          # same list object: no copy happens
b.append(4)
print(a)       # the append is visible through a
c = a[:]       # a slice makes an explicit (shallow) copy
c.append(99)
print(a)       # a stays untouched
print(c)
Output
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4, 99]

Rust v1.99.1

v1.99.1
// Vec has no copy-on-write: assignment moves ownership, clone is the
// explicit copy, and after the move the original is gone
fn main() {
    let a = vec![1, 2, 3];
    let mut b = a.clone();
    b.push(4);
    println!("{}", a.len()); // 3: a unaffected by b
    println!("{}", b.len()); // 4
    let c = a; // move: ownership transfers, a is no longer usable
    println!("{}", c.len()); // 3
}
Output
3
4
3

TypeScript v26.13.1

v26.13.1
const a: number[] = [1, 2, 3];
const b = a;    // the same array: no copy happens
b.push(4);
console.log(a.join(",")); // the push is visible through a
const c = [...a];         // spread makes an explicit shallow copy
c.push(99);
console.log(a.join(",")); // a stays untouched
console.log(c.join(","));
Output
1,2,3,4
1,2,3,4
1,2,3,4,99

Language differences

C: pointer semantics (example): the array name decays to a pointer and assignment shares memory; copying is a manual memcpy with hand-managed size, and resizing does not exist — push-style helpers reserve capacity and carry a length themselves.

C++: eager value semantics (example): vector assignment deep-copies immediately, no copy-on-write; mutating the copy and the original are independent — the same semantics as PHP with the opposite performance strategy (PHP shares until a write, C++ allocates at assignment); COW has to be hand-rolled with shared_ptr plus write checks.

C#: reference sharing (example): arrays and List<T> assignments share the object and writes show through every reference; an explicit copy is new List<T>(original) or ToList(); no language-level COW (ImmutableArray and friends take the immutability road instead).

Go: slice-header sharing (example): assignment copies the {pointer,len,cap} triple and shares the backing array — element writes are mutually visible (the first assertion, 99 99); append reallocating past capacity detaches the slice (the second assertion, 99 7); a single expression may either share or detach, and that is the core trap of Go array semantics.

Java: reference sharing (example): arrays and ArrayList assignments share the object; explicit copies are new ArrayList<>(original) or clone(); Arrays.asList adds a wrapped-view third way; no language-level COW.

JavaScript: reference sharing (example): array assignment shares the object; explicit copies use spread [...a], slice(), or Array.from() (all shallow); no language-level COW; deep copies need structuredClone.

PHP: value semantics plus COW (example): assignment behaves as a full copy — mutating either side never affects the other (first assertion); under the hood the engine reference-counts and separates only on write, invisible to user code (is_refcounted/refcount are debug-only); pass-by-reference &$ (second assertion) is the one regular way to break COW explicitly — referenced arrays share storage and mutate in place; foreach as &$v does the same (demonstrated in this series' foreach entry).

Python: reference sharing (example): list assignment shares the object; explicit copies are a[:] / list(a) / copy.copy (shallow — nested structures stay shared); copy.deepcopy for the full thing; no language-level COW.

Rust: move semantics (example): Vec assignment moves ownership — the original variable fails to compile afterwards, so a runtime state where two names reference the same array simply cannot exist; both sides usable means an explicit clone; a shared mutable view goes through &mut exclusive borrows; Rc<RefCell<Vec>> simulates sharing — the language eradicates accidental sharing at compile time.

TypeScript: at the language level the same as JS (example): reference sharing plus explicit shallow copies; readonly T[] / ReadonlyArray<T> forbid push and friends at the type level — the read-only view is a compile-time expression over the very same runtime array; ReadonlyMap/ReadonlySet follow the same idea.