Conceptcore
Reference counting
Also called refcounting, RC, reference-counted pointer, shared ownership, automatic reference counting.
Reference counting stores in each object the number of references to it and frees the object when the number reaches zero. Objects in a cycle never reach zero.
- Applies to
- core-languages
Idea
Some objects have more than one user. A buffer can be read by a parser and kept by a cache at the same time. No single part of the program knows when the last user is done, so no single part can free the buffer safely. Reference counting solves this with a number in each object: the count of references that point to it. Each added reference adds one, and each reference that goes away subtracts one. When the count reaches zero, nothing can reach the object any more, and the object is freed at that moment.1
CPython keeps such a count for every object. The count lives in the header of the object.4 In this run, two list entries add two references, and clearing the list removes them. The object is freed on the line that drops its last name.
import sys
class Buffer:
def __del__(self):
print("buffer freed")
buffer = Buffer()
base = sys.getrefcount(buffer)
users = [buffer, buffer]
print("references added by the list:", sys.getrefcount(buffer) - base)
users.clear()
print("back to the start:", sys.getrefcount(buffer) == base)
print("before del")
del buffer
print("after del")
references added by the list: 2
back to the start: True
before del
buffer freed
after del
The example compares two counts instead of printing one, because sys.getrefcount includes the temporary reference to its own argument.5 Reference counting is one of the two main ways of automatic memory management. The other is the tracing collection that Garbage collection describes.
How it works
Every reference-counted object carries a count, and two operations change it. Retain (increment) runs when the program stores a reference in a variable, a field or a container. Release (decrement) runs when such a reference goes away. The release that brings the count to zero frees the object. Before the memory goes, the object releases the references that it holds itself. That can bring other counts to zero, so one release can free a whole structure.16
before: report and cache both refer to Page
report ─┐
├──> Page (count 2) ──> Header (count 1)
cache ─┘
release report: Page (count 1) nothing is freed
release cache: Page (count 0) free Page
└─ release Header: Header (count 0) free Header
RETAIN(x) ▷ a new reference to x- 1
count(x) ← count(x) + 1 RELEASE(x) ▷ one reference to x goes away- 2
count(x) ← count(x) − 1 - 3
if count(x) = 0 then - 4
for each reference from x to an object y do RELEASE(y) - 5
if weak(x) = 0 then free the memory of x - 6
else destroy the value of x and keep its memory for the weak references
Who calls retain and release depends on the language. In C code that uses CPython, the programmer calls Py_INCREF to take a strong reference and Py_DECREF to give it back. When the last strong reference goes, Py_DECREF calls the deallocation function of the type of the object.3 Python code never calls them: the interpreter does it as values move through variables and containers. A Rust Rc or a C++ shared_ptr is a value that owns one reference. Its copy (Rc::clone, the copy constructor) retains, and its drop or destructor releases.1013 Swift and Objective-C under ARC let the compiler insert the retains and releases.917
Weak references. A weak reference points to an object but does not add to its count. So it does not keep the object alive. Before use, the program must turn it into a strong reference, and that step fails when the object is gone. Rust calls this upgrade on a Weak, and it returns None after the value is dropped.10 C++ calls it weak_ptr::lock, which returns an empty shared_ptr when the object has expired.15 A Swift weak reference is always optional, and ARC sets it to nil when the instance is freed.9 To answer "is it gone?", the runtime keeps a second count, of weak references. In Rust, a Weak keeps the allocation alive but not the value inside it.10 That is line L6 of the pseudocode.
The limit: cycles. A count tells how many references point to an object, not whether the program can still reach it. Two objects that refer to each other each keep a count of at least one, even after the program has lost both. Reference counting alone never frees a cycle. The Rust standard library says that a cycle of Rc pointers will never be deallocated. For a tree, it suggests strong pointers from parents to children and Weak pointers from children to parents.10 CPython adds a cycle collector for this case, and Swift and Objective-C leave it to the programmer.8917
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Standard library | |
| Java | Idiom | |
| C | Idiom | |
| C# | Idiom | |
| JavaScript | Idiom | |
| TypeScript | Idiom | |
| Go | Idiom | |
| Rust | Standard library | |
| Kotlin | Idiom | Kotlin/JVM and Kotlin/Native free memory with a tracing collector, and objects have no reference counts; a count for a shared resource uses AtomicInteger on the JVM, as in Java; no example file because kotlinc is not installed on the machine that recorded the examples. Alternative: Use for a resource with one owner, which closes it at the end of a scope. |
| SQL | Does not apply | A query has no references to objects; the database engine manages its own storage. |
| Bash | Does not apply | A script holds strings and arrays, not references to objects. Alternative: The file system counts the hard links of a file, and it frees the file when the count is 0 and no process has the file open. |
| PowerShell | Absent | The .NET collector frees objects, and a script has no reference counts; no example file because pwsh is not installed on the machine that recorded the examples. Alternative: Dispose a shared resource in a finally block, or call System.Threading.Interlocked from a .NET class as in C#. |
| HTML | Does not apply | Markup has no objects; the DOM belongs to the JavaScript engine. |
| CSS | Does not apply | Style rules have no objects. |
| Regular expressions | Does not apply | A pattern has no objects. |
The example files show the native and standard library forms in Python, Rust, C++ and C. The languages with a tracing collector have no counts for memory. Their files use a count for a resource instead: a shared connection that closes when its last user releases it.
| Language | Verdict | Form |
|---|---|---|
| Python | native | CPython: a count in each object header, a cycle collector for cycles; immortal objects keep a fixed count46 |
| Rust | stdlib | Rc (plain counts, single thread) and Arc (atomic counts), with Weak for both1012 |
| C++ | stdlib | std::shared_ptr and std::weak_ptr; std::make_shared puts the object and the counts in one allocation1314 |
| C | idiom | a count field in the struct, with retain and release functions that every caller pairs by hand |
| Java | idiom | tracing collector; AtomicInteger counts the users of a resource19 |
| JavaScript | idiom | tracing collector; a plain number counts the users of a resource |
| TypeScript | idiom | as JavaScript |
| C# | idiom | tracing collector; Interlocked.Increment and Interlocked.Decrement count the users of a resource21 |
| Go | idiom | tracing collector; sync/atomic counts the users of a resource20 |
| Kotlin | idiom | the collector of the platform; on the JVM, AtomicInteger as in Java |
| PowerShell | absent | the .NET collector frees objects; scripts dispose resources instead |
| Bash | n/a | a script has no references to objects |
| SQL | n/a | a query has no references to objects |
| Regex | n/a | a pattern has no objects |
| HTML/CSS | n/a | markup and style have no objects |
In CPython, each object starts with its reference count and a pointer to its type.4 The C API says to trust only the values 0 and 1, because some objects are immortal and report a very high count.3 The free-threaded build changes the representation, as the Variations section describes, but not the rule.7
Rust and C++ make shared ownership a library type. Most values have one owner and need no count (see Ownership and borrowing and Resource acquisition is initialization). Rc<T>, Arc<T> and shared_ptr<T> are for a value with several owners, where no owner is known to outlive the others. Rc::strong_count and Rc::weak_count read the two counts, and shared_ptr::use_count reads the strong count.1113 With several threads, the value of use_count is only approximate.13
C has no smart pointers, so a library writes the count into its own structs. It documents which functions return a reference that the caller must release. A missing release is a memory leak. An extra release frees the object while a pointer to it is still in use, which leads to a Use after free. These are the errors of Manual memory management, one level up.
Java, JavaScript, TypeScript, C#, Go and Kotlin free memory with a tracing collector. A count still helps for a resource that must close at a known time, such as a connection or a file. With Thread, each change of the count must be one atomic step. Otherwise two threads can read the same old value, and the resource closes twice or never. The example files use the atomic types of each standard library.192021
import sys
class Node:
def __init__(self, name, child=None):
self.name = name
self.child = child
def __del__(self):
print("freed", self.name)
head = Node("first", Node("second", Node("third")))
second = head.child
base = sys.getrefcount(second)
alias = second
print("one more reference:", sys.getrefcount(second) - base)
del alias, second
print("drop head")
del head
print("done")
one more reference: 1
drop head
freed first
freed second
freed third
done
- Verdict: native. CPython stores a reference count in the header of each object, and it frees the object when the count reaches zero. A cycle collector frees the groups of objects that refer to each other.
del headremoves the last reference to the first node. Its deallocation drops the reference to the second node, which then has a count of zero too, so the whole chain goes in one step.sys.getrefcountcounts its own argument, so compare two calls in the same place instead of reading one value.- The free-threaded build splits the count into a part for the thread that owns the object and a shared part for other threads.
#include <memory>
#include <print>
#include <string>
struct Order {
std::string id;
~Order() { std::println("destroy {}", id); }
};
int main() {
std::weak_ptr<Order> probe;
{
auto order = std::make_shared<Order>("order 42");
auto copy = order;
probe = order;
std::println("use_count {}", order.use_count());
if (auto locked = probe.lock()) {
std::println("locked {}, use_count {}", locked->id, locked.use_count());
}
copy.reset();
std::println("use_count after reset {}", order.use_count());
}
std::println("expired {}", probe.expired());
std::println("lock is empty {}", probe.lock() == nullptr);
}
use_count 2
locked order 42, use_count 3
use_count after reset 1
destroy order 42
expired true
lock is empty true
- Verdict: stdlib.
std::shared_ptrcounts theshared_ptrobjects that own one object. The last owner to go destroys the object. std::make_sharedmakes the object and the owner in one call. The standard asks it to do no more than one allocation.std::weak_ptrdoes not own the object.lock()returns an owner while the object exists, and an emptyshared_ptrafter it is gone.- Copies of a
shared_ptrin different threads are not a data race, so the library changes the count with atomic operations.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
static class Connection {
private final AtomicInteger users = new AtomicInteger(1);
private volatile boolean open = true;
Connection retain() {
users.incrementAndGet();
return this;
}
void release() {
if (users.decrementAndGet() == 0) {
open = false;
System.out.println("connection closed");
}
}
}
public static void main(String[] args) throws InterruptedException {
Connection conn = new Connection();
List<Thread> workers = new ArrayList<>();
for (int i = 0; i < 4; i++) {
Connection mine = conn.retain();
workers.add(Thread.ofPlatform().start(mine::release));
}
for (Thread worker : workers) {
worker.join();
}
System.out.println("open after workers: " + conn.open);
conn.release();
System.out.println("open after last release: " + conn.open);
}
}
open after workers: true
connection closed
open after last release: false
- Verdict: idiom. The JVM frees memory with a tracing collector, so Java has no reference counts for objects. A count is still useful for a resource that must close when its last user is done.
AtomicInteger.decrementAndGetchanges the count as one atomic step, so two threads cannot both see the same old value.- Each worker gets its reference before its thread starts, so the count cannot reach zero while a worker still waits to run.
- For a resource with one owner, try-with-resources is the usual form; see Resource acquisition is initialization.
#include <stdio.h>
#include <stdlib.h>
struct buffer {
int refs;
char name[16];
};
struct buffer *buffer_new(const char *name) {
struct buffer *b = malloc(sizeof *b);
if (b != NULL) {
b->refs = 1;
snprintf(b->name, sizeof b->name, "%s", name);
}
return b;
}
struct buffer *buffer_retain(struct buffer *b) {
b->refs++;
return b;
}
void buffer_release(struct buffer *b) {
if (--b->refs == 0) {
printf("free %s\n", b->name);
free(b);
}
}
int main(void) {
struct buffer *b = buffer_new("frame");
if (b == NULL) {
return 1;
}
struct buffer *reader = buffer_retain(b);
struct buffer *writer = buffer_retain(b);
printf("refs %d\n", b->refs);
buffer_release(b);
buffer_release(writer);
printf("refs %d\n", reader->refs);
buffer_release(reader);
printf("done\n");
}
refs 3
refs 1
free frame
done
- Verdict: idiom. C has no reference counts. A library puts a count in the struct and gives a retain function and a release function, and every caller must pair them by hand.
buffer_newreturns the buffer with a count of 1, for the caller. The release that brings the count to zero frees the struct.- A missing release is a leak, and an extra release frees the struct while another pointer still uses it.
- The plain
intcount is for one thread. A buffer that threads share needs an atomic count.
var conn = new Connection();
var workers = new List<Task>();
for (int i = 0; i < 4; i++)
{
Connection mine = conn.Retain();
workers.Add(Task.Run(mine.Release));
}
await Task.WhenAll(workers);
Console.WriteLine($"open after workers: {conn.IsOpen}");
conn.Release();
Console.WriteLine($"open after last release: {conn.IsOpen}");
class Connection
{
private int users = 1;
public bool IsOpen => Volatile.Read(ref users) > 0;
public Connection Retain()
{
Interlocked.Increment(ref users);
return this;
}
public void Release()
{
if (Interlocked.Decrement(ref users) == 0)
{
Console.WriteLine("connection closed");
}
}
}
open after workers: True
connection closed
open after last release: False
- Verdict: idiom. .NET frees memory with a tracing collector, so C# objects have no reference counts. A count still helps when several users share one resource.
Interlocked.Decrementdecrements the field and returns the result as one atomic operation, so only one caller sees zero.- Each task gets its reference before it starts. Without that, a fast task could close the connection while the loop still hands it out.
- For one owner, the
usingstatement disposes the object at the end of its scope.
class Connection {
#users = 1;
open = true;
retain() {
this.#users += 1;
return this;
}
release() {
this.#users -= 1;
if (this.#users === 0) {
this.open = false;
console.log("connection closed");
}
}
}
async function work(conn, id) {
await Promise.resolve();
console.log(`request ${id} done`);
conn.release();
}
const conn = new Connection();
const requests = [1, 2, 3].map((id) => work(conn.retain(), id));
await Promise.all(requests);
console.log("open after requests:", conn.open);
conn.release();
console.log("open after last release:", conn.open);
request 1 done
request 2 done
request 3 done
open after requests: true
connection closed
open after last release: false
- Verdict: idiom. JavaScript engines free memory with a tracing collector, and the language has no reference counts. A program can count the users of a resource itself.
- This program runs on one thread, so a plain number is enough for the count.
- Each request takes its reference before it starts to wait. The last
releasecloses the connection, whatever the order in which the requests end. - A
FinalizationRegistrycallback is not a replacement, because the collector decides when it runs.
class Connection {
#users = 1;
open = true;
retain(): this {
this.#users += 1;
return this;
}
release(): void {
this.#users -= 1;
if (this.#users === 0) {
this.open = false;
console.log("connection closed");
}
}
}
async function work(conn: Connection, id: number): Promise<void> {
await Promise.resolve();
console.log(`request ${id} done`);
conn.release();
}
const conn = new Connection();
await Promise.all([1, 2, 3].map((id) => work(conn.retain(), id)));
console.log("open after requests:", conn.open);
conn.release();
console.log("open after last release:", conn.open);
request 1 done
request 2 done
request 3 done
open after requests: true
connection closed
open after last release: false
- Verdict: idiom. TypeScript compiles to JavaScript, and the engine frees memory with a tracing collector. A count for a shared resource is ordinary code.
- The types do not track the count. Nothing stops a call of
releasetoo many times, or a missing one. retainreturnsthis, so the call site takes its reference in the same expression that passes the connection on.
package main
import (
"fmt"
"sync"
"sync/atomic"
)
type connection struct {
users atomic.Int32
closed atomic.Bool
}
func open() *connection {
c := &connection{}
c.users.Store(1)
return c
}
func (c *connection) retain() *connection {
c.users.Add(1)
return c
}
func (c *connection) release() {
if c.users.Add(-1) == 0 {
c.closed.Store(true)
fmt.Println("connection closed")
}
}
func main() {
conn := open()
var wg sync.WaitGroup
for range 4 {
mine := conn.retain()
wg.Go(mine.release)
}
wg.Wait()
fmt.Println("closed after workers:", conn.closed.Load())
conn.release()
fmt.Println("closed after last release:", conn.closed.Load())
}
closed after workers: false
connection closed
closed after last release: true
- Verdict: idiom. Go frees memory with a tracing collector and has no reference counts for objects. A program can count the users of a resource by hand.
atomic.Int32.Addreturns the value after the change, so exactly one goroutine sees zero and closes the connection.- The count goes up in
mainbefore each goroutine starts, so a quick goroutine cannot bring it to zero early. - For one owner,
defer conn.Close()is the usual form.
use std::rc::Rc;
use std::sync::Arc;
use std::thread;
fn main() {
let order = Rc::new(String::from("order 42"));
let shared = Rc::clone(&order);
let probe = Rc::downgrade(&order);
println!("strong {}, weak {}", Rc::strong_count(&order), Rc::weak_count(&order));
drop(shared);
drop(order);
println!("value alive: {}", probe.upgrade().is_some());
let total = Arc::new(vec![1, 2, 3]);
let workers: Vec<_> = (0..3)
.map(|_| {
let total = Arc::clone(&total);
thread::spawn(move || total.iter().sum::<i32>())
})
.collect();
let sums: Vec<i32> = workers.into_iter().map(|w| w.join().unwrap()).collect();
println!("sums {:?}, strong count after join {}", sums, Arc::strong_count(&total));
}
strong 2, weak 1
value alive: false
sums [6, 6, 6], strong count after join 1
- Verdict: stdlib.
RcandArcin the standard library count the owners of one heap allocation.Rc::cloneadds an owner, and the drop of an owner removes one. Rc::downgrademakes aWeakpointer. It adds to the weak count, not to the strong count, andupgradereturnsNoneafter the value is dropped.Rcuses plain counts and is notSend, so the compiler rejects it inthread::spawn.Arcuses atomic counts. Each thread drops its clone when it ends, so the count is 1 again afterjoin.- Most Rust values have one owner and need no count; see Ownership and borrowing.
Variations and related ideas
- Compiler-inserted counts. Objective-C objects have
retainandreleasemethods. Under ARC, the compiler inserts these calls, and ARC has no cycle collector.17 Swift ARC counts references to class instances only. Structures and enumerations are value types and have no count.9 - Strong, weak and unowned. Swift has three kinds of reference. A strong reference keeps the instance alive. A weak reference does not, and becomes
nilwhen the instance goes. An unowned reference does not keep the instance alive either, but it is not optional. It is for an instance with the same or a longer lifetime. An access after that instance is freed is a runtime error.9 - Cycle collection. CPython keeps reference counting and adds a pass that finds cycles. For each container object in the set that it scans, it copies the count and subtracts each reference that comes from inside the set. An object that keeps a count above zero has a reference from outside. The collector keeps it and everything that it reaches, and frees the rest.8
- Deferred reference counting. Deutsch and Bobrow kept the counts accurate only when storage was about to be reclaimed. They wrote the count changes to a transaction file and kept counts only for items with more than one reference.2 The free-threaded CPython build defers the counts of top-level functions, code objects, modules and methods. The interpreter skips their count updates when it pushes them on its stack and pops them. The true count is then known only when all threads pause for a collection, so these objects are freed only during collection.7
- Biased reference counting. Most objects are used by one thread only. The free-threaded build gives each object an owner thread. The owner changes a local count with plain instructions. Other threads change a shared count with atomic instructions. The two counts are merged before the object can be freed.7
- Immortal objects. CPython marks some objects, such as
None, with a fixed count.Py_INCREFandPy_DECREFdo not change it, so the object is never freed while the runtime runs.63sys._is_immortalreports whether an object is immortal.5 - Intrusive and separate counts. A CPython object, a C struct with a count field and an Objective-C object hold their count inside the object. A
shared_ptrmade from a raw pointer must keep its counts elsewhere.std::make_sharedshould do only one allocation, and the standard notes that this gives the efficiency of an intrusive smart pointer.14 - The unique-owner test. A count of one means that no one else can see the value. Rust uses this in
Rc::get_mut, which returns a mutable reference only when there are no otherRcorWeakpointers.11Arc::make_mutclones the value only when it is shared.12 - File system links. A POSIX file has a link count.
unlinkremoves a name and decrements the count. The file system frees the file when the count is 0 and no process has the file open.18
Pitfalls
A cycle never reaches zero
A tree where each child holds a strong pointer to its parent is a cycle. The parent owns the child, and the child owns the parent. When main drops its own pointers, both counts stay above zero. No drop line prints, and both folders leak until the process ends.
This code runs but gives a wrong answer on purpose.
use std::cell::RefCell;
use std::rc::Rc;
struct Folder {
name: String,
parent: Option<Rc<Folder>>,
children: RefCell<Vec<Rc<Folder>>>,
}
impl Drop for Folder {
fn drop(&mut self) {
println!("drop {}", self.name);
}
}
fn main() {
let root = Rc::new(Folder { name: "root".into(), parent: None, children: RefCell::new(Vec::new()) });
let docs = Rc::new(Folder { name: "docs".into(), parent: Some(Rc::clone(&root)), children: RefCell::new(Vec::new()) });
root.children.borrow_mut().push(Rc::clone(&docs));
println!("root strong count: {}", Rc::strong_count(&root));
drop(docs);
drop(root);
println!("end of main");
}
root strong count: 2
end of main
The fix makes the link up the tree weak. The parent owns its children, and a child only observes its parent. The drop of root brings its count to zero, and the release of its children drops docs in turn.10
use std::cell::RefCell;
use std::rc::{Rc, Weak};
struct Folder {
name: String,
parent: Weak<Folder>,
children: RefCell<Vec<Rc<Folder>>>,
}
impl Drop for Folder {
fn drop(&mut self) {
println!("drop {}", self.name);
}
}
fn main() {
let root = Rc::new(Folder { name: "root".into(), parent: Weak::new(), children: RefCell::new(Vec::new()) });
let docs = Rc::new(Folder { name: "docs".into(), parent: Rc::downgrade(&root), children: RefCell::new(Vec::new()) });
root.children.borrow_mut().push(Rc::clone(&docs));
println!("root strong {}, weak {}", Rc::strong_count(&root), Rc::weak_count(&root));
if let Some(parent) = docs.parent.upgrade() {
println!("parent of docs: {}", parent.name);
}
drop(docs);
drop(root);
println!("end of main");
}
root strong 1, weak 1
parent of docs: root
drop root
drop docs
end of main
The same leak happens with shared_ptr in C++ and with strong references in Swift.9 In CPython, the cycle collector frees the strong version, but only when it runs.
A weak reference outlives its target
A weak reference is not a promise that the object exists. Code that assumes the target is there fails after the owner lets it go. Here a request keeps a weak reference to its session, and the session ends first.
This code raises AttributeError, on purpose.
import weakref
class Session:
def __init__(self, user):
self.user = user
class Request:
def __init__(self, session):
self.session = weakref.ref(session)
def user(self):
return self.session().user
session = Session("ada")
request = Request(session)
print(request.user())
del session
print(request.user())
The call self.session() returns None once the session is freed, and None has no user attribute. Check the result of the upgrade every time, and decide what the code does when the target is gone. In Rust, match on the Option from upgrade instead of calling unwrap. In C++, test the shared_ptr from lock before use.1015
import weakref
class Session:
def __init__(self, user):
self.user = user
class Request:
def __init__(self, session):
self.session = weakref.ref(session)
def user(self):
session = self.session()
if session is None:
return "no session"
return session.user
session = Session("ada")
request = Request(session)
print(request.user())
del session
print(request.user())
ada
no session
An Rc cannot cross threads
Rc changes its counts with plain operations. Two threads that clone one Rc at the same time could lose an update, and the value would be freed too early or never. So Rc does not implement Send, and the compiler rejects the program.10
This code does not compile, on purpose.
use std::rc::Rc;
use std::thread;
fn main() {
let config = Rc::new(String::from("mode=fast"));
let copy = Rc::clone(&config);
let worker = thread::spawn(move || copy.len());
println!("{}", worker.join().unwrap());
}
Arc changes its counts with atomic operations, so it can go to another thread. Arc makes the ownership thread-safe, not the value. A value that threads change still needs a Mutex or an atomic type.12 See Data race.
use std::sync::Arc;
use std::thread;
fn main() {
let config = Arc::new(String::from("mode=fast"));
let copy = Arc::clone(&config);
let worker = thread::spawn(move || copy.len());
println!("{}", worker.join().unwrap());
println!("strong count after join: {}", Arc::strong_count(&config));
}
9
strong count after join: 1
sys.getrefcount counts its own argument
sys.getrefcount returns a count that is generally one higher than expected, because the call holds a temporary reference to its argument.5 Here only one name refers to the order, but the test for "only one reference" fails.
This code runs but gives a wrong answer on purpose.
import sys
order = {"id": 42}
print("only one reference:", sys.getrefcount(order) == 1)
only one reference: False
The exact value also depends on the interpreter, and immortal objects report a very large count. The documentation says not to rely on the value except for 0 or 1.5 To check that some code adds or removes a reference, compare two counts taken the same way.
import sys
order = {"id": 42}
before = sys.getrefcount(order)
pending = [order]
print("added by the list:", sys.getrefcount(order) - before)
pending.clear()
print("removed again:", sys.getrefcount(order) == before)
added by the list: 1
removed again: True
Two owner groups for one object
A shared_ptr made from a raw pointer starts an owner group with a count of 1.13 A second shared_ptr made from the same raw pointer starts a second group, with its own count. Each group deletes the object when its own count reaches zero, so the object is deleted twice. The second delete is undefined behaviour. AddressSanitizer reports it as a double free.
This code has a memory error, on purpose, and the sanitizer reports it.
#include <memory>
#include <print>
struct Session {
int user_id = 7;
};
int main() {
Session* raw = new Session;
std::shared_ptr<Session> first(raw);
std::shared_ptr<Session> second(raw);
std::println("{} {}", first.use_count(), second.use_count());
}
The fix makes the object with std::make_shared and copies the shared_ptr, never the raw pointer. A member function that must hand out an owner of its own object has the same problem with shared_ptr<Session>(this). The class derives from std::enable_shared_from_this instead, and shared_from_this() returns an owner in the existing group.1416
#include <memory>
#include <print>
struct Session : std::enable_shared_from_this<Session> {
int user_id = 7;
std::shared_ptr<Session> self() { return shared_from_this(); }
};
int main() {
auto first = std::make_shared<Session>();
auto second = first;
auto third = first->self();
std::println("{} {} {}", first.use_count(), second.use_count(), third.use_count());
}
3 3 3
shared_from_this() works only on an object that a shared_ptr already owns. On any other object it throws std::bad_weak_ptr.1613
Cost
- A count in each object. In a normal CPython build, the header of every object holds the reference count and a pointer to the type.4 The free-threaded build adds fields. It stores the owner thread id, a 4-byte local count, a shared count, a 1-byte mutex and a byte of collector flags.7
- A shared_ptr is two pointers wide. The
shared_ptrmust reach both the object and its counts. In this run it is twice the size of a raw pointer. The standard does not fix this size.
#include <memory>
#include <print>
int main() {
std::println("shared_ptr / raw pointer: {}", sizeof(std::shared_ptr<int>) / sizeof(int*));
std::println("weak_ptr / raw pointer: {}", sizeof(std::weak_ptr<int>) / sizeof(int*));
}
shared_ptr / raw pointer: 2
weak_ptr / raw pointer: 2
- A write for each copy. Each retain and each release writes to the object, even when the program only reads the object. PEP 683 notes that every change of a count invalidates the cache line of the object. Two threads on different cores that use one object invalidate each other's caches with each increment and decrement, even when neither thread changes the object.6 The writes also reduce the memory that processes share after
fork, because copy-on-write copies each page where a count changes.6 - Atomic counts. Each clone and each drop of an
Arc, and each copy and destruction of ashared_ptr, is an atomic read-modify-write. The Rust documentation says that atomic operations "are more expensive than ordinary memory accesses", and suggestsRcwhen no allocation is shared between threads.12 The C++ standard lets threads copyshared_ptrobjects of the same owner group without a data race, so the library must update the count atomically.13 When many threads copy one pointer, they all write one cache line, and the line moves from core to core.6 PEP 703 calls such atomic read-modify-write operations "expensive on contemporary processors", and uses biased counting to avoid many of them.7 - Work at the moment of the release. The release of the head of a long list frees the whole list in one step. So the time of one release can grow with the size of the structure. A release can also run code. In CPython, a deallocation can run a
__del__method, so C code must leave its data consistent before it callsPy_DECREF.3 - No pause to find garbage. In exchange, memory comes back as soon as the last reference goes. The program does not wait for a collector to find garbage. Cycles are the exception: they need a cycle collector or a design with weak links.
History
- 1960. George E. Collins described reference counts for lists that share ("overlap") their parts. The counts record how far the lists overlap, so the system can erase a list without erasing the parts that other lists still use.1
- 1976. L. Peter Deutsch and Daniel G. Bobrow described a collector for Lisp in which reference counts need to be accurate only when storage is about to be reclaimed. It kept a transaction file of count changes and a table for the items with more than one reference.2
- 2018. Jiho Choi, Thomas Shull and Josep Torrellas described biased reference counting, at PACT 2018, as PEP 703 records.7
- 2022. PEP 683 proposed immortal objects for CPython, with a fixed count that
Py_INCREFandPy_DECREFdo not change. It was accepted for Python 3.12.6 - 2023. PEP 703 was accepted on 24 October 2023 for Python 3.13. It makes the global interpreter lock optional. In the build without the lock, it uses biased counting, immortal objects and a limited form of deferred counting.7
References
- George E. Collins, A method for overlapping and erasure of lists, Communications of the ACM 3(12), 1960, the reference count of each list cell and erasure when the count reaches zero
- L. Peter Deutsch and Daniel G. Bobrow, An efficient, incremental, automatic garbage collector, Communications of the ACM 19(9), 1976, abstract, reference counts that need to be accurate only when storage is about to be reclaimed, the transaction file and the multiple reference table
- The Python/C API Reference Manual, Reference Counting, Python 3.14, Py_REFCNT, Py_INCREF, Py_DECREF and its warning
- The Python/C API Reference Manual, Common Object Structures, Python 3.14, PyObject and PyObject.ob_refcnt
- The Python Standard Library, sys, Python 3.14, sys.getrefcount and sys._is_immortal
- PEP 683: Immortal Objects, Using a Fixed Refcount, Abstract; Motivation, Reducing CPU Cache Invalidation and Avoiding Copy-on-Write; Specification; Public Refcount Details; the header fields Created and Python-Version
- PEP 703: Making the Global Interpreter Lock Optional in CPython, Reference Counting; Immortalization; Biased Reference Counting; Deferred Reference Counting; Integration With Deferred and Biased Reference Counting; the header fields Python-Version and Resolution
- CPython InternalDocs, Garbage collector design, Identifying reference cycles
- The Swift Programming Language, Automatic Reference Counting, the introduction; How ARC Works; Weak References; Unowned References
- The Rust Standard Library, module std::rc, module documentation, the paragraphs on non-atomic counts, Send, Weak and cycles
- The Rust Standard Library, struct std::rc::Rc, downgrade, weak_count, strong_count, get_mut
- The Rust Standard Library, struct std::sync::Arc, struct description and Thread Safety
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [util.smartptr.shared.general] paragraphs 1 and 5; [util.smartptr.shared.const] paragraphs 6 to 8; [util.smartptr.shared.dest]; [util.smartptr.shared.obs] use_count
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [util.smartptr.shared.create] paragraph 7.1
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [util.smartptr.weak.general] and [util.smartptr.weak.obs] expired and lock
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [util.smartptr.enab] paragraphs 1 and 7, shared_from_this
- Clang documentation, Objective-C Automatic Reference Counting (ARC), Background (retain, release and autorelease) and General
- The Open Group Base Specifications Issue 8 (POSIX.1-2024), unlink, DESCRIPTION
- Java SE 25 API, java.util.concurrent.atomic.AtomicInteger, incrementAndGet() and decrementAndGet()
- Go standard library, package sync/atomic, package overview and type Int32, method Add
- .NET API, Interlocked.Decrement Method, the summary of the overloads
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 3VCXKD Edit this page History Report an error Markdown