Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

References & ownership

Borrow access or pass an address

C++

T& is a reference, T* a pointer, &value an address and *pointer a dereference. For pointers, p->member means (*p).member; pointer-like classes may overload ->. References/pointers can dangle if the object dies first. const T& restricts writes through that reference.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
void increment(int& value) {
    value += 1;
}

int count = 2;
increment(count);
int* pointer = &count;

struct Flag { bool active; };
Flag flag{true};
Flag* handle = &flag;
const bool ready = handle->active;

Recognize owning and shared handles

C++

unique_ptr has exclusive ownership; shared_ptr reference-counts shared ownership; weak_ptr observes without owning. Moving a unique_ptr transfers its ownership. Raw pointers do not express an ownership policy by themselves.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <memory>
#include <utility>

auto owned = std::make_unique<int>(24);
auto moved = std::move(owned);

auto shared = std::make_shared<int>(24);
auto another = shared;

Read lifetime-related notation

C++

A reference/view does not extend every source object’s lifetime. Returning a view of a local string would leave it dangling. In this example, storage remains alive for the entire use of the view.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <string>
#include <string_view>

std::string owned = "north";
std::string_view view = owned;

// Use view while owned remains alive and valid.

Copy or move a value: reference semantics, value copies, move, Copy/Clone, std::move

C++

Beyond recognizing copies (the copying entry), this covers how copy and move operations work and when to write them yourself. Objects are values: initialization and assignment call the copy constructor or copy assignment, which for standard containers copies every element. C++11 added moves: std::move is only a cast to an rvalue reference, and the move constructor or move assignment that it selects may steal the source's resources. A moved-from standard library object is in a valid but unspecified state: operations without preconditions (size(), clear(), assignment) work, but do not assume its value; reassign or clear it before reuse. The rule of zero says a class whose members manage themselves (string, vector, unique_ptr) should declare none of the five special members; the rule of five says a class that defines a destructor, copy or move operation should consider all five.

Complete program

Complete program (C++23).

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <print>
#include <string>
#include <utility>
#include <vector>

// Rule of zero: members manage themselves, so the compiler-generated copy, move and
// destructor are correct. Prefer this for almost every type.
struct Route {
    std::string id;
    std::vector<int> stops;
};

// Rule of five: a class that owns a raw resource must define (or delete) all five.
class Buffer {
public:
    explicit Buffer(std::size_t n) : size_(n), data_(new int[n]{}) {}
    ~Buffer() { delete[] data_; }

    Buffer(const Buffer& other) : size_(other.size_), data_(new int[other.size_]) {
        std::copy(other.data_, other.data_ + size_, data_);  // deep copy
    }
    Buffer(Buffer&& other) noexcept  // steal, then leave `other` empty but valid
        : size_(std::exchange(other.size_, 0)), data_(std::exchange(other.data_, nullptr)) {}
    Buffer& operator=(Buffer other) noexcept {  // copy-and-swap covers copy and move assignment
        std::swap(size_, other.size_);
        std::swap(data_, other.data_);
        return *this;
    }

    std::size_t size() const { return size_; }
    int& operator[](std::size_t i) { return data_[i]; }

private:
    std::size_t size_;
    int* data_;
};

int main() {
    Route a{"R1", {0, 12}};
    Route b = a;  // copy: independent string and vector
    b.stops.push_back(20);
    assert(a.stops.size() == 2);

    Route c = std::move(a);  // move: c takes a's buffers
    // a is "valid but unspecified": don't assume its value; reassign or clear it before reuse.
    a = Route{"R9", {}};
    std::println("{} {} {} {}", a.id, b.stops.size(), c.id, c.stops.size());

    Buffer x(3);
    x[0] = 42;
    Buffer y = x;             // copy constructor
    y[0] = 7;
    Buffer z = std::move(x);  // move constructor: x.size() is now 0 because we wrote it that way
    std::println("{} {} {} {}", y[0], z[0], z.size(), x.size());
    x = y;                    // a moved-from object can be assigned again
    std::println("{}", x[0]);
}

In practice: write rule-of-zero types, pass large inputs by const T& (or by value and std::move when you keep a copy), and mark move operations noexcept so vector can use them when it grows.

std::move on a const object silently copies, because a const T&& cannot bind to T&&.

Declaring a destructor or copy operation suppresses the implicit move operations, so the class silently copies where it would have moved.

Do not write return std::move(local); it blocks copy elision. Plain return local; already moves.

clang-tidy (bugprone-use-after-move) catches many reads of a moved-from object.

Choose an owning pointer: GC references, Box/Rc/Arc/Weak, unique_ptr/shared_ptr/weak_ptr

C++

Beyond recognizing handles (the ownership entry), this says which owning pointer to pick and how functions should accept it. <memory> provides the owning pointers. unique_ptr<T> is the single owner: move-only, the same size as a raw pointer with the default deleter, and it deletes the object in its destructor. shared_ptr<T> counts owners in a control block (atomic, so copies are thread-safe, but the pointee is not); make_shared allocates the object and the count together. weak_ptr<T> observes a shared_ptr without owning; lock() returns an empty shared_ptr once the object is gone. Raw pointers and references remain the way to pass a non-owning view.

Complete program

Complete program (C++23).

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cassert>
#include <memory>
#include <print>
#include <string>
#include <utility>
#include <vector>

struct Shape {
    virtual ~Shape() = default;
    virtual double area() const = 0;
};
struct Square : Shape {
    double side;
    explicit Square(double s) : side(s) {}
    double area() const override { return side * side; }
};

// A factory returns unique_ptr: the caller becomes the single owner.
std::unique_ptr<Shape> make_square(double side) { return std::make_unique<Square>(side); }

// A function that only uses the object takes a reference (or raw pointer): non-owning.
double doubled_area(const Shape& s) { return 2 * s.area(); }

struct Team;
struct Member {
    std::string name;
    std::weak_ptr<Team> team;  // back edge: observe, don't own, so the cycle can be freed
};
struct Team {
    std::string name;
    std::vector<std::shared_ptr<Member>> members;
};

int main() {
    std::unique_ptr<Shape> shape = make_square(3);
    std::vector<std::unique_ptr<Shape>> shapes;
    shapes.push_back(std::move(shape));  // ownership moves; shape is now null
    assert(shape == nullptr);
    std::println("{}", doubled_area(*shapes[0]));  // 18

    auto team = std::make_shared<Team>(Team{"core", {}});
    auto ada = std::make_shared<Member>(Member{"ada", team});
    team->members.push_back(ada);  // copying a shared_ptr bumps the count
    std::println("{} {}", ada.use_count(), team.use_count());  // 2 1

    if (auto t = ada->team.lock()) std::println("{} is on {}", ada->name, t->name);
    team.reset();  // the last owner releases the Team
    assert(ada->team.expired());
    std::println("{}", ada.use_count());  // 1: the Team's vector was destroyed with it
}

In practice: default to unique_ptr from make_unique, and convert to shared_ptr only when ownership is truly shared. Take const T& or T* in functions that only use the object; take unique_ptr by value only when the function takes ownership. Use weak_ptr for back pointers and caches.

Never create two shared_ptrs from the same raw pointer; each has its own count and both delete. Inherit enable_shared_from_this to get a shared_ptr to this.

shared_ptr cycles leak like Rc cycles; break them with weak_ptr.

With make_shared, the memory of the object stays allocated until the last weak_ptr is gone, because it shares the control block.

Mutate shared state safely: aliasing, pointer receivers, &mut, RefCell/Mutex, const

C++

Beyond passing references (the references entry), this covers what const promises, and what it does not, when several names reach one object. C++ permits any aliasing and checks none of it. const is the tool for stating intent: a const T& parameter promises not to write through it, and a const member function can be called on a const object and cannot change its members (except mutable ones). const does not mean the object cannot change: another, non-const alias may change it, and a const& parameter may even refer to part of the object you are modifying. Writing through a reference or iterator after the container reallocated is undefined behavior. Unsynchronized writes from two threads are a data race, also undefined.

Complete program

Complete program (C++23).

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <algorithm>
#include <cassert>
#include <functional>
#include <print>
#include <span>
#include <vector>

class Ledger {
public:
    void add(int cents) { entries_.push_back(cents); }
    // const member function: callable through const Ledger&, cannot change members.
    int total() const { return std::ranges::fold_left(entries_, 0, std::plus{}); }
    // Return a read-only view; callers cannot mutate the internals through it.
    std::span<const int> entries() const { return entries_; }

private:
    std::vector<int> entries_;
};

void report(const Ledger& ledger) {  // const&: no copy, and no writes
    std::println("total {} over {} entries", ledger.total(), ledger.entries().size());
    // ledger.add(1);  // error: 'this' argument to member function 'add' has type
    //                 // 'const Ledger', but function is not marked const
}

// Aliasing pitfall: `factor` may refer to an element of `values`.
void scale_by_ref(std::vector<double>& values, const double& factor) {
    for (double& v : values) v *= factor;  // after values[0] changes, so does factor
}
// Fix: take the scalar by value, so it is a private copy.
void scale(std::vector<double>& values, double factor) {
    for (double& v : values) v *= factor;
}

int main() {
    Ledger ledger;
    ledger.add(10);
    ledger.add(-3);
    report(ledger);

    std::vector<double> a{2, 3, 4};
    scale_by_ref(a, a[0]);  // factor reads 2, then 4 after a[0] became 4
    std::println("{}", a);  // [4, 12, 16]
    std::vector<double> b{2, 3, 4};
    scale(b, b[0]);
    std::println("{}", b);  // [4, 6, 8]

    // Worse aliasing: a reference into a vector across push_back is undefined behavior.
    // const double& first = b[0]; b.push_back(first); b.push_back(first);  // may reallocate
    double first = b[0];  // copy the value before growing the vector
    b.push_back(first);
    assert(b.back() == 4);
}

In practice: mark every member function that does not modify state const and take read-only inputs as const T&. Take small scalars by value, so they cannot alias your output. Do not keep references into a container across insertions. Guard shared data with std::mutex and std::scoped_lock.

A mutable member can change in a const function; it is meant for caches and mutexes, and then the class must synchronize it.

Build with -fsanitize=thread to find data races and -fsanitize=address for use after reallocation.

const_cast to write to an object that was defined const is undefined behavior.

std::ranges::fold_left is C++23 (GCC 13+, libc++ 18+); std::accumulate from <numeric> does the same on older libraries.

Printing containers with std::println needs range formatting: GCC 15+ or libc++ 17+.

Avoid dangling references: stale handles, loop captures, borrow errors, use-after-free

C++

Beyond reading lifetime notation (the lifetime-notes entry), this lists the common ways a reference, view or iterator dangles and how to avoid each. References, pointers, iterators and views (string_view, span) do not keep their target alive, and using one after the target is destroyed or moved is undefined behavior: it may print the right answer, garbage or crash. The common cases are returning a reference or view to a local, binding a string_view or span to a temporary that dies at the end of the full expression, and iterator invalidation: push_back or insert on a vector may reallocate and invalidate every iterator, pointer and reference into it, and erase invalidates the erased position and everything after it.

Complete program

Complete program (C++23). The buggy versions are in comments.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cassert>
#include <print>
#include <string>
#include <string_view>
#include <vector>

// BUG (dangling): returns a reference to a local that is destroyed on return.
// const std::string& label(int id) { std::string s = "job-" + std::to_string(id); return s; }
// clang: warning: reference to stack memory associated with local variable 's' returned
// Fix: return by value (moves or elides the copy).
std::string label(int id) { return "job-" + std::to_string(id); }

// BUG: string_view to a temporary; the std::string dies at the end of the statement.
// std::string_view name = label(7);  // name now points at freed memory
// clang: warning: object backing the pointer will be destroyed at the end of the full-expression
// Fix: keep an owning string; use string_view only while the owner lives.
std::size_t count_dashes(std::string_view text) {  // fine: the caller's string outlives the call
    std::size_t n = 0;
    for (char c : text) n += (c == '-');
    return n;
}

int main() {
    std::string name = label(7);
    std::println("{} {}", name, count_dashes(name));  // job-7 1

    std::vector<int> jobs{1, 2, 3};

    // BUG (iterator invalidation): push_back may reallocate, invalidating `it` and `&jobs[0]`.
    // for (auto it = jobs.begin(); it != jobs.end(); ++it) if (*it == 2) jobs.push_back(20);
    // Fix: iterate by index over the original size.
    for (std::size_t i = 0, n = jobs.size(); i < n; ++i)
        if (jobs[i] == 2) jobs.push_back(20);

    // BUG: erase() invalidates the erased iterator, so ++it afterwards is undefined.
    // for (auto it = jobs.begin(); it != jobs.end(); ++it) if (*it % 2 == 0) jobs.erase(it);
    // Fix: std::erase_if (C++20), or `it = jobs.erase(it)` without incrementing.
    std::erase_if(jobs, [](int j) { return j % 2 == 0; });
    std::println("{}", jobs);  // [1, 3]

    // A pointer kept across growth is stale too; store an index instead.
    std::size_t first = 0;
    jobs.reserve(100);
    jobs.push_back(5);
    assert(jobs[first] == 1);
}

In practice: return by value. Store owning types (std::string, std::vector) in members, and use string_view and span only for parameters and short-lived locals. Iterate by index when the loop adds elements, use std::erase_if or it = v.erase(it) when it removes them, and compile tests with -fsanitize=address.

clang warns about some cases (-Wreturn-stack-address, -Wdangling-gsl) but not iterator invalidation; AddressSanitizer catches it at run time.

A range-for over a temporary's member, for (auto x : make().items()), dangled before C++23; C++23 extends the temporary's lifetime in the range initializer.

Lambdas that capture by reference ([&]) and outlive the scope, for example in a thread or callback, dangle the same way.

Printing containers with std::println needs range formatting: GCC 15+ or libc++ 17+.

Release resources by ownership: using and Symbol.dispose, Close conventions, Drop, RAII and deleters

C++

Beyond recognizing destructors (the cleanup entry), this shows how to write the owners themselves: unique_ptr with a deleter and move-only classes. RAII ties a resource to an object: the constructor acquires, the destructor releases, and the language runs destructors at scope exit and during exception unwinding, in reverse order of construction. Ownership of the resource then follows the object: a move-only owner (copy deleted, move leaves the source empty) can be returned from factories and passed into functions without double release. For C handles, std::unique_ptr with a custom deleter is a ready-made owner; an empty deleter struct keeps it pointer-sized.

Complete program

Complete program (C++23). Uses std::tmpfile, which deletes itself on close.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cassert>
#include <cstdio>
#include <memory>
#include <print>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

// A unique_ptr with a custom deleter turns a C handle into an RAII owner.
// An empty deleter struct adds no size, unlike a function-pointer deleter.
struct FileCloser {
    void operator()(std::FILE* f) const noexcept { std::fclose(f); }
};
using File = std::unique_ptr<std::FILE, FileCloser>;

// The factory hands ownership to the caller; if it throws, nothing was acquired.
File open_temp() {
    File f{std::tmpfile()};
    if (!f) throw std::runtime_error("tmpfile failed");
    return f;
}

std::vector<std::string> events;

// A hand-written owner: move-only, release in the destructor.
class Lease {
public:
    explicit Lease(std::string name) : name_(std::move(name)) { events.push_back("acquire " + name_); }
    ~Lease() {
        if (!name_.empty()) events.push_back("release " + name_);
    }
    Lease(Lease&& other) noexcept : name_(std::exchange(other.name_, {})) {}
    Lease& operator=(Lease&&) = delete;
    Lease(const Lease&) = delete;  // copying would release twice
    Lease& operator=(const Lease&) = delete;

private:
    std::string name_;
};

// Taking the owner by value: the parameter is released when consume returns.
void consume(Lease) { events.push_back("consume"); }

int main() {
    File f = open_temp();
    std::fputs("hello", f.get());
    std::rewind(f.get());
    char buf[8]{};
    std::fgets(buf, sizeof buf, f.get());
    std::println("{}", std::string_view{buf});
    File other = std::move(f);  // ownership moves; f is empty, only `other` will fclose
    assert(!f && other);

    {
        Lease a("a");
        Lease b("b");
        consume(std::move(b));  // b is now empty; its destructor does nothing
    }  // destruction in reverse order of construction: b (empty), then a
    try {
        Lease c("c");
        throw std::runtime_error("boom");
    } catch (const std::exception&) {
        events.push_back("caught");  // c was released during unwinding, before the handler
    }
    for (const auto& e : events) std::print("{}; ", e);
    std::println();
}

In practice: never pair acquire and release by hand in business code; wrap each handle once, in unique_ptr with a deleter or a small move-only class, and let it follow the rule of zero elsewhere. Destructors are noexcept by default, so report release errors through an explicit close() if callers need them.

A destructor that throws during unwinding calls std::terminate.

If a constructor throws, the destructor of that object does not run, but its already-constructed members and bases are destroyed; this is why each resource should live in its own member owner.

std::unique_ptr<FILE, decltype(&std::fclose)> works too, but stores the function pointer; the deleter struct is free.