Programming Search⌘K

Conceptcore

Ownership and borrowing

Also called ownership, borrowing, borrow checker, move semantics, unique ownership, single owner, owning pointer, non-owning reference.

Ownership makes one part of a program responsible for releasing each value, and other code borrows the value for a limited time. Rust checks these rules at compile time.

Applies to
core-languages

Idea

Every piece of memory, every open file and every lock must be released one time, at the right time. Ownership is the rule that says which part of a program is responsible for that release. The owner of a value frees it. Other code can borrow the value, which means that it uses the value for a limited time and does not free it. If two parts of a program both think that they own a value, it is freed twice. If no part owns it, it is never freed. If a borrower keeps the value after the owner frees it, the borrower reads freed memory. Even in a language with a garbage collector, a program needs to know who may change a value. If code keeps a reference to a list that it does not own, a change by the real owner can surprise it:

class Playlist:
    def __init__(self, songs):
        self.songs = songs


class OwnedPlaylist:
    def __init__(self, songs):
        self.songs = list(songs)


songs = ["intro", "theme"]
shared = Playlist(songs)
owned = OwnedPlaylist(songs)
songs.clear()
print(shared.songs)
print(owned.songs)
Output
[]
['intro', 'theme']

Playlist borrows the list of the caller and keeps the borrow. OwnedPlaylist makes its own copy and owns it. Most languages leave these rules to documentation and conventions. C++ puts ownership into library types. Rust checks ownership and borrowing in the compiler.

How it works

One owner. The Rust book gives three rules: "Each value in Rust has an owner. There can only be one owner at a time. When the owner goes out of scope, the value will be dropped."1 With one owner, the time of the release is known from the program text. It is the end of the scope of the owner, as in RAII. No garbage collector and no reference count is necessary.

Moves. An owner can give its value to a new owner. In Rust, assignment and a call by value move the value, and the compiler rejects any later use of the old name. In C++, std::unique_ptr "owns (is responsible for) and manages another object via a pointer and subsequently disposes of that object when the unique_ptr goes out of scope".2 It can be moved but not copied, and a move "transferring ownership from u to *this ... stores the null pointer in u."3 The move is the transfer of the duty to free. JavaScript has the same idea for a few resource types: "Transferable objects are objects that own resources that can be transferred from one context to another, ensuring that the resources are only available in one context at a time. Following a transfer, the original object is no longer usable".4

Borrows. Code that only needs a value for a short time gets a reference and not the value. The Rust book states: "We call the action of creating a reference borrowing. As in real life, if a person owns something, you can borrow it from them. When you're done, you have to give it back."5 In C++, the Core Guidelines give the same meaning to plain pointers and references: "R.3: A raw pointer (a T*) is non-owning" and "R.4: A raw reference (a T&) is non-owning".6 A borrower must not free the value, and it must not use the value after the owner frees it.

Aliasing rules. Rust adds a second rule for borrows: "At any given time, you can have either one mutable reference or any number of immutable references. References must always be valid."5 Many readers or one writer is the same rule as a reader-writer lock, and the compiler checks it before the program runs. The book states that the benefit of this restriction is that "Rust can prevent data races at compile time."5 The rule also prevents a common single-threaded bug: a reference into a vector that becomes invalid when the vector grows and moves its elements.

Lifetimes. To check that a borrow does not outlive its owner, the compiler gives each reference a lifetime, which is the region of the program where the reference is used. A function signature can name lifetimes to say, for example, that the result borrows from the first argument. Most lifetimes are inferred.

In languages

LanguageVerdictNote
PythonAbsent
C++Standard library
JavaAbsent
CAbsent
C#Absent
JavaScriptAbsent
TypeScriptAbsentAs JavaScript; readonly types block writes through one reference, but they do not track an owner. Alternative: Transferable objects such as ArrayBuffer, as in JavaScript.
GoAbsent
RustNative
KotlinAbsentThe garbage collector frees objects, and references do not own them; no example file because kotlinc is not installed on the machine that recorded the examples. Alternative: The use function closes a Closeable at the end of a block.
SQLDoes not applyA query works on rows in tables, and the database engine owns all storage.
BashDoes not applyBash variables hold strings and arrays by value, and a script has no references to memory.
PowerShellAbsent.NET objects are shared through references and freed by the garbage collector; no example file because pwsh is not installed on the machine that recorded the examples. Alternative: Call Dispose in a finally block for objects that hold resources.
HTMLDoes not applyHTML has no memory or references.
CSSDoes not applyCSS has no memory or references.
Regular expressionsDoes not applyA regular expression has no memory or references.
Language Verdict Mechanism
Python absent garbage collection, weakref, with blocks
JavaScript absent garbage collection, transferable objects
TypeScript absent as JavaScript, readonly types
Java absent garbage collection, defensive copies
Kotlin absent garbage collection, use
C# absent garbage collection, Span<T> and ref struct
Go absent garbage collection, slices.Clone
Rust native moves, & and &mut borrows, the borrow checker
C absent documented conventions, const pointers
C++ stdlib std::unique_ptr, move semantics, non-owning raw pointers
Bash n/a no references to memory
PowerShell absent garbage collection, Dispose
SQL n/a the database engine owns storage
Regex, HTML, CSS n/a no memory or references

Rust is the main language with checked ownership. Moves, borrows and lifetimes are part of the type system, and a program that breaks the rules does not compile.1

C++ has ownership in the library. std::unique_ptr is the single owner, std::shared_ptr is shared ownership with a reference count, and plain pointers, references and std::span are borrows by convention.6 The compiler does not check that a borrow lives shorter than its owner.

C has no ownership in the language. Each API documents which pointers the caller must free.

Python, JavaScript, TypeScript, Java, Kotlin, Go and PowerShell use a garbage collector, so no reference owns memory. Ownership still matters for resources such as files and sockets, and for mutable data that several parts of a program share. These languages use copies, immutable values and blocks such as with and try-with-resources.

C# also uses a garbage collector, but Span<T> gives a checked form of borrowing. A span is a ref struct, and instances of such a type "can't escape to the managed heap".7

Go slices are views of a shared array. "Slicing does not copy the slice's data. It creates a new slice value that points to the original array."8 A function that keeps a slice must copy it if the caller can change the array.

PythonGitHub
import weakref


class Frame:
    def __init__(self, name):
        self.name = name


owner = Frame("frame 1")
view = weakref.ref(owner)
print(view().name)
del owner
print(view())
Output
frame 1
None
  • Verdict: absent. All references to an object are equal, and the garbage collector frees the object when no reference remains. No reference owns the object.
  • A weak reference does not keep its object alive, so it acts as a non-owning view. In CPython, reference counting frees the object at once when the last strong reference goes.
  • A with block owns a resource, such as a file, for the duration of the block, and closes it at the end.
#include <iostream>
#include <memory>
#include <string>
#include <vector>

struct Track {
    std::string name;
};

class Playlist {
public:
    void add(std::unique_ptr<Track> track) { tracks_.push_back(std::move(track)); }
    const Track* first() const { return tracks_.front().get(); }

private:
    std::vector<std::unique_ptr<Track>> tracks_;
};

int main() {
    auto track = std::make_unique<Track>(Track{"intro"});
    Playlist playlist;
    playlist.add(std::move(track));
    std::cout << (track == nullptr ? "moved, now null" : "still owned") << "\n";

    const Track* view = playlist.first();
    std::cout << view->name << "\n";
}
Output
moved, now null
intro
  • Verdict: stdlib. std::unique_ptr owns one object and deletes it when it goes out of scope. It can be moved and cannot be copied, so the type system makes sure that there is one owner.
  • A function that takes std::unique_ptr<T> by value takes ownership. A raw pointer or a reference is a non-owning view by convention, as the C++ Core Guidelines recommend.
  • The compiler does not check that a view lives shorter than its owner. Moved-from objects can also still be used, and for std::unique_ptr the moved-from value is null.
#include <memory>

int main() {
    int* raw = new int(7);
    std::unique_ptr<int> a(raw);
    std::unique_ptr<int> b(raw);
}

Two unique_ptr objects take ownership of the same pointer, and both delete it. The double delete is undefined behavior. Make the owner at the point of allocation with std::make_unique, and never give a raw pointer to a second owner.

JavaGitHub
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> tracks = new ArrayList<>(List.of("intro", "theme"));
        List<String> view = Collections.unmodifiableList(tracks);
        List<String> copy = List.copyOf(tracks);

        tracks.add("outro");
        System.out.println(view);
        System.out.println(copy);
    }
}
Output
[intro, theme, outro]
[intro, theme]
  • Verdict: absent. The garbage collector frees objects, and every reference can read and write the object. A class that must not share mutable state keeps a defensive copy.
  • An unmodifiable view blocks writes through the view, but the owner can still change the data. List.copyOf makes an immutable copy that no other code can change.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Returns a new string. The caller owns it and must free it. */
static char *make_greeting(const char *name) {
    size_t size = strlen("hello, ") + strlen(name) + 1;
    char *text = malloc(size);
    if (text != NULL) {
        snprintf(text, size, "hello, %s", name);
    }
    return text;
}

/* Borrows the string. It does not keep or free it. */
static size_t count_vowels(const char *text) {
    size_t count = 0;
    for (; *text != '\0'; text++) {
        count += strchr("aeiou", *text) != NULL;
    }
    return count;
}

int main(void) {
    char *greeting = make_greeting("ada");
    if (greeting == NULL) {
        return 1;
    }
    printf("%s has %zu vowels\n", greeting, count_vowels(greeting));
    free(greeting);
    greeting = NULL;
    return 0;
}
Output
hello, ada has 4 vowels
  • Verdict: absent. A C pointer does not say if it owns the memory. The API documentation states who frees each pointer, and const marks a pointer that only reads.
  • The compiler does not check the rules. Static analyzers and sanitizers find some double frees, leaks and uses after free.
int[] samples = [1, 2, 3, 4, 5, 6];
Span<int> middle = samples.AsSpan(2, 3);
Scale(middle, 10);
Console.WriteLine(string.Join(",", samples));
Console.WriteLine(Sum(samples));

static void Scale(Span<int> values, int factor)
{
    foreach (ref int value in values)
    {
        value *= factor;
    }
}

static int Sum(ReadOnlySpan<int> values)
{
    int total = 0;
    foreach (int value in values)
    {
        total += value;
    }
    return total;
}
Output
1,2,30,40,50,6
129
  • Verdict: absent. The garbage collector owns all objects. Span<T> and ReadOnlySpan<T> are borrows of a part of an array or of other memory, and they do not copy.
  • A span is a ref struct. The compiler does not let it escape to the heap, for example as a field of a class, so a span cannot outlive the method that gets it.
  • For other resources, the convention is that the code which makes an IDisposable disposes of it, usually with using.
JavaScriptGitHub
const buffer = new ArrayBuffer(4);
new Uint8Array(buffer)[0] = 42;

const moved = structuredClone(buffer, { transfer: [buffer] });
console.log(buffer.byteLength, buffer.detached);
console.log(new Uint8Array(moved)[0]);

const again = moved.transfer();
console.log(moved.detached, again.byteLength);

try {
  new Uint8Array(moved);
} catch (e) {
  console.log(e.constructor.name);
}
Output
0 true
42
true 4
TypeError
  • Verdict: absent. Objects are shared through references, and the garbage collector frees them. The language has no owner for an ordinary object.
  • Transferable objects, such as ArrayBuffer, MessagePort and streams, are the exception. A transfer moves the resource to a new object or to another worker, and the old object becomes detached and unusable.
package main

import (
	"fmt"
	"slices"
)

func main() {
	all := []int{1, 2, 3, 4}
	head := slices.Clone(all[:2])
	head = append(head, 99)
	fmt.Println(all, head)

	limited := all[:2:2]
	limited = append(limited, 7)
	fmt.Println(all, limited)
}
Output
[1 2 3 4] [1 2 99]
[1 2 3 4] [1 2 7]
  • Verdict: absent. The garbage collector frees memory, and a slice is a view of a shared array. A slice does not show if it owns its array.
  • slices.Clone gives the new slice its own array. A full slice expression, s[low:high:max], limits the capacity, so that append must copy.

This code runs but gives a wrong answer on purpose.

package main

import "fmt"

func main() {
	all := []int{1, 2, 3, 4}
	head := all[:2]
	head = append(head, 99)
	fmt.Println(all)
}
Output
[1 2 99 4]

head shares the array of all and has spare capacity, so append writes over the third element of all.

RustGitHub
fn total(items: &[u32]) -> u32 {
    items.iter().sum()
}

fn add_tax(items: &mut Vec<u32>) {
    for item in items.iter_mut() {
        *item += *item / 10;
    }
}

fn consume(items: Vec<u32>) -> usize {
    items.len()
}

fn main() {
    let mut prices = vec![100, 250];
    println!("{}", total(&prices));
    add_tax(&mut prices);
    println!("{:?}", prices);

    let moved = prices;
    println!("{}", consume(moved));
}
Output
350
[110, 275]
2
  • Verdict: native. Each value has one owner. Assignment and a call by value move the value to a new owner, and the old name can no longer be used. When the owner goes out of scope, the value is dropped.
  • &T is a shared borrow and &mut T is a unique borrow. The borrow checker accepts many shared borrows or one unique borrow at a time, and no borrow can live longer than the owner.

This code does not compile, on purpose.

fn main() {
    let names = vec![String::from("a")];
    let other = names;
    println!("{} {}", names.len(), other.len());
}

The compiler rejects the program with error E0382, borrow of moved value. After let other = names, the vector belongs to other. To keep both, clone the vector, or borrow it with &names.

This code does not compile, on purpose.

fn main() {
    let mut scores = vec![1, 2, 3];
    let first = &scores[0];
    scores.push(4);
    println!("{first}");
}

The compiler rejects the program with error E0502. push can move the elements to a new buffer, and first would then point to freed memory. In C++, the same code compiles and has undefined behavior.

Shared ownership. A value can have many owners and be freed when the last owner goes. std::shared_ptr in C++, Rc and Arc in Rust, and Swift classes use reference counting for this.

Interior mutability. Rust types such as RefCell and Mutex check the aliasing rule at run time, for data structures that the compile-time rule rejects.

Linear and affine types. A linear value must be used exactly once, and an affine value at most once. Rust moves are affine: a program can drop a value without using it. Linear types are the theory under ownership.

Regions. A region is a block of memory that holds many objects and is freed as a whole. Region systems check that no pointer into a region outlives the region.9

Ownership modifiers. Swift adds borrowing and consuming parameter modifiers, which let a function state if it borrows or takes ownership of an argument.10

Garbage collection. A garbage collector removes the need to decide which reference owns memory. It does not remove the need to manage other resources and shared mutable state.

Pitfalls

Use after move. In C++, a moved-from object still exists and can be used. A moved-from std::unique_ptr is null, and other types are left in a valid but unspecified state. Rust rejects any use after a move at compile time.

Two owners. If two owning objects get the same raw pointer, both free it. In C++, make the owner at the point of allocation with std::make_unique, and never pass a raw pointer to a second owner.

A borrow that outlives the owner. A pointer, reference, iterator or view that the owner invalidates becomes dangling. Common causes are a reference into a vector that grows, a std::string_view of a temporary string, and a pointer to a local variable that a function returns. Rust rejects these programs. C and C++ compile them, and the result is undefined behavior.

A hidden shared view. In garbage-collected languages, a stored reference to a list, an array or a slice is a shared view, and not a copy. If the caller later changes the data, the stored view changes too. Copy the data at the boundary if the code must own it.

Fights with the borrow checker. Some correct programs break the Rust rules, for example a graph with parent and child links, or two mutable references into different parts of one structure. The usual answers are indices into a vector, Rc with RefCell, methods such as split_at_mut, or unsafe code behind a safe interface.

Cycles with shared ownership. Two values that own each other through reference counts are never freed. One of the links must be a weak reference.

Cost

Single ownership costs nothing at run time. A move copies the bytes of a handle, such as a pointer and a length, and not the data that it points to. A borrow is a plain pointer. The release happens at a known point, so there is no garbage collector pause and no reference count update. The cost is at compile time and for the programmer: some designs need more thought, and code that shares data freely must use shared ownership, which costs a count update for each copy of the handle.

History

Philip Wadler proposed linear types for functional languages in 1990: "Values belonging to a linear type must be used exactly once: like the world, they cannot be duplicated or destroyed. Such values require no reference counting or garbage collection, and safely admit destructive array update."11 Ownership types for object-oriented languages, which control which objects may refer to the internal objects of another object, came from the work of David Clarke, John Potter and James Noble in 1998. Cyclone, a safe dialect of C, used regions and static checks of pointer lifetimes in 2002.9 C++ had ownership conventions for a long time, and C++11 added move semantics and std::unique_ptr. Rust combined unique ownership, borrowing and lifetimes into one checked system, and Rust 1.0 was released in 2015. Swift, Mojo and other languages have since added ownership features of their own.10

References

  1. The Rust Programming Language, 4.1 What Is Ownership?, Rust 1.99.1, Ownership Rules
  2. std::unique_ptr, cppreference.com, description
  3. std::unique_ptr<T,Deleter>::unique_ptr, cppreference.com, overload 5
  4. Transferable objects, MDN Web Docs, introduction
  5. The Rust Programming Language, 4.2 References and Borrowing, Rust 1.99.1, The Rules of References
  6. C++ Core Guidelines, B. Stroustrup and H. Sutter, editors, R.3 and R.4
  7. ref structure types, C# language reference, Microsoft Learn, introduction
  8. Go Slices: usage and internals, The Go Blog, Slice internals
  9. Region-Based Memory Management in Cyclone, D. Grossman, G. Morrisett, T. Jim, M. Hicks, Y. Wang and J. Cheney, PLDI 2002, Abstract
  10. SE-0377, borrowing and consuming parameter ownership modifiers, Swift Evolution, Introduction
  11. Linear types can change the world!, P. Wadler, Programming Concepts and Methods, North Holland, 1990, abstract

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/37GYNK/text.yaml