Skip to content

Cpp 04 ownership

Mugundan edited this page Nov 27, 2026 · 1 revision

Ownership and Move Semantics

Relevant source files

The following files were used as context for generating this wiki page:

Every object must eventually be destroyed exactly once. Ownership answers "who destroys it?". Modern C++ makes the owner explicit with std::unique_ptr and transfers ownership cheaply with move semantics. LLVM adds its own rule on top: most IR objects are owned by their parent (a module owns its functions, a block owns its instructions), so you rarely delete anything yourself.

Purpose and Scope

This page covers stack versus heap, raw pointers versus owning pointers, std::unique_ptr, std::move and rvalue references, moved-from objects, and how ownership works for LLVM IR objects. Containers are on LLVM Data Structures.

The House Deed Analogy

Property C++
A house has exactly one deed An object has exactly one owner (unique_ptr)
Visitors may know the address without owning it Raw pointers and references are non-owning
Selling the house hands over the deed; the seller has none left Moving a unique_ptr
When the owner leaves for good, the house is demolished The owner's destructor deletes the object

Stack and Heap

flowchart LR
    subgraph Stack["Stack: automatic"]
        S1["int X = 5;"]
        S2["SmallVector<int, 8> V;"]
    end
    subgraph Heap["Heap: dynamic"]
        H1["new Node / make_unique<Node>()"]
    end
    S1 -.->|"freed when scope ends"| E1["automatic"]
    H1 -.->|"freed when the owner is destroyed"| E2["unique_ptr destructor"]
Loading
Stack Heap
Lifetime Ends at the closing } Until someone deletes it
Speed Very fast Allocation costs time
Size Must be known at compile time, keep it modest Any

Prefer the stack. When you need the heap, let a unique_ptr own the object. Avoid writing new and delete by hand.

unique_ptr and Move

// example: move
#include "llvm/Support/raw_ostream.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
using namespace llvm;

struct Node {
  std::string Name;
  explicit Node(std::string N) : Name(std::move(N)) { outs() << "make " << Name << "\n"; }
  ~Node() { outs() << "free " << Name << "\n"; }
};

std::unique_ptr<Node> build(const char *N) { return std::make_unique<Node>(N); }

int main() {
  std::unique_ptr<Node> A = build("a");
  std::unique_ptr<Node> B = std::move(A);      // ownership moves to B
  outs() << "A is " << (A ? "set" : "empty") << ", B owns " << B->Name << "\n";
  std::vector<std::unique_ptr<Node>> List;
  List.push_back(std::move(B));                 // now the vector owns it
  List.push_back(build("b"));
  outs() << "list size " << List.size() << "\n";
}                                               // vector destroyed: frees both
make a
A is empty, B owns a
make b
list size 2
free a
free b
sequenceDiagram
    participant A as A
    participant B as B
    participant L as List
    A->>B: std::move(A): B owns "a", A is null
    B->>L: push_back(std::move(B)): List owns "a"
    L->>L: end of main: List destroys its elements
Loading
Operation Allowed? Why
auto B = A; (copy a unique_ptr) No, compile error Two owners would delete twice
auto B = std::move(A); Yes Ownership transfers; A becomes null
Node *Raw = B.get(); Yes A non-owning pointer for looking
B.release() Yes, but rarely Gives up ownership without deleting: now you must delete

Sources: cppreference: std::unique_ptr

What std::move Really Does

std::move(X) does not move anything by itself. It only casts X to an rvalue reference (T &&), meaning "you may steal from this". The type's move constructor then steals the contents, for example a std::string's heap buffer, instead of copying them.

Expression Category Meaning
X (a named variable) lvalue Has a name; still used later, so copy it
std::move(X), a returned temporary rvalue About to disappear, so its insides can be taken

After a move, the source is in a "valid but unspecified" state: you may assign to it or destroy it, but don't read its value. (unique_ptr is a special case: a moved-from one is guaranteed to be null.)

Returning a local by value (return Result;) moves or elides the copy automatically; don't write return std::move(Result);.

Sources: cppreference: std::move, cppreference: Value categories

Ownership in LLVM IR

flowchart TD
    C["LLVMContext<br/>owns types and constants"] --- M["Module<br/>(often held in std::unique_ptr&lt;Module&gt;)"]
    M -->|"owns"| F["Function"]
    F -->|"owns"| BB["BasicBlock"]
    BB -->|"owns"| I["Instruction"]
Loading
Task Call Effect
Create and insert an instruction IRBuilder or X::Create(..., InsertBefore) The parent block owns it
Unlink and destroy I->eraseFromParent() Removes from the block and deletes
Unlink but keep I->removeFromParent() Now you own it and must insert or delete it
Load a module parseIRFile(...) returns std::unique_ptr<Module> You own the module

So in a pass you hold plain Instruction * pointers that don't own anything, and you never delete an instruction directly. Before erasing, make sure nothing still uses it: call I->replaceAllUsesWith(New) first. Keeping a pointer to an erased instruction is a dangling pointer, the most common crash in new passes.

LLVM's casting functions even have a unique_ptr overload, cast<To>(std::unique_ptr<From> &&), which moves ownership while it casts.

Sources: llvm/include/llvm/Support/Casting.h:577

Common Traps

  • Using a variable after std::move from it.
  • Keeping Instruction * pointers in a container and then erasing those instructions.
  • std::shared_ptr "to be safe": LLVM code almost never needs shared ownership, and it costs reference counting.
  • Taking a StringRef or ArrayRef to a temporary that dies at the end of the statement (see LLVM Data Structures).

Key Points

  • Every object has one owner; unique_ptr makes that explicit and deletes automatically.
  • std::move casts to an rvalue so the contents can be taken; don't read a moved-from object.
  • IR objects are owned by their parent; use eraseFromParent, not delete, and replace uses first.

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally