Skip to content

Ownership graphs and lifetime design

Difficulty: Advanced

Key concepts

  • ownership graph
  • lifetime
  • back-reference
  • parent pointer
  • cross-reference
  • stable identifier
  • borrowing
  • dangling pointer
  • ownership cycle
  • How to draw an ownership graph for objects that are created, moved, and deleted while the program runs, with three kinds of edge: owns, points to, and names by id.
  • Why the owning edges should form a tree, and what to do when a relationship does not fit one.
  • How a child can point back to its parent safely, and who must keep that pointer correct.
  • Why a reference across the tree is usually better as an id than a pointer.
  • How to keep an index of pointers in step with the objects it points at.
  • How to write borrowing rules that tell a caller how long a returned reference stays valid.

On the composition-root page every object was built at the start and destroyed at the end, in a fixed order. Most real data is not like that. Here is a small document editor’s model:

  • D1 A document has sections in order; each section has paragraphs in order.
  • D2 A paragraph can be moved to the end of another section. It keeps its links and comments.
  • D3 A paragraph or a whole section can be deleted.
  • D4 A paragraph can link to another paragraph. The text shows the target’s current number, such as “see 2.1”.
  • D5 A comment is attached to a paragraph. If the paragraph is deleted, the comment stays and says so.
  • D6 Code that has a paragraph can ask which section it is in.

A first design that “just uses pointers” looks reasonable:

Each pointer has a lifetime bug waiting for one of the requirements:

  • Parents that move. sections holds Section values. Adding a section can make the vector grow, which moves every section to new memory. Every Paragraph::section now points at freed memory. Containers and complexity shows this invalidation.
  • Children that move. The same happens one level down. Adding a paragraph can move all the paragraphs of its section; deleting one moves the paragraphs after it down by one; moving one to another section (D2) copies it to a new address. Links and comments now point at freed memory, or worse, at a different paragraph that moved into the old place.
  • References that outlive their target. Deleting a paragraph (D3) leaves every comment and link to it pointing at a destroyed object. Nothing says which pointers must be cleared, and they are spread across the document.

The common first fix is to make every pointer a std::shared_ptr. That stops the dangling and adds two new problems. A section’s shared_ptr keeps its paragraphs alive and each paragraph’s shared_ptr keeps its section alive, so neither count reaches zero and deleting a section frees nothing: an ownership cycle. And a comment’s shared_ptr keeps a deleted paragraph alive, so the comment cannot tell that it was deleted (D5).

None of this shows up in a test that never deletes or adds anything. The fix is not cleverer pointers; it is a decision, for each relationship, about who destroys whom, and when. The ownership graph is where that decision is made.

Step 1: draw the graph with three kinds of edge

Section titled “Step 1: draw the graph with three kinds of edge”

An ownership graph has the objects as boxes and three kinds of edge:

  • Owns: the source destroys the target. A std::unique_ptr member, a value member, or an element of a container held by value.
  • Points to: the source holds a raw pointer or a reference to the target, and does not destroy it.
  • Names by id: the source holds an identifier, and has to ask an owner to turn it into an object. If the object is gone, the owner says so.

Then classify each relationship from the requirements. For each one, ask: which side is destroyed first, and can that order change while the program runs?

Relationship Requirement Which is destroyed first? Edge
document → section D1, D3 the section, always (deleted, or with the document) owns, through std::unique_ptr
section → paragraph D1, D2, D3 the paragraph, always (deleted, or with its section) owns, through std::unique_ptr
paragraph → its section D6 the paragraph, always: its section owns it points to, kept correct by the document on a move
paragraph → linked paragraph D4 either one; any paragraph can be deleted at any time names by id
comment → paragraph D5 the paragraph may go first, and the comment must stay names by id
document → comment D5 the comment owns, as a value
document’s index → each paragraph D4, D5, D6 the paragraph; the document removes the entry first points to, kept in step by the document

The rule behind the choices:

  1. Owning edges form a tree. Every object has exactly one owner, and following owning edges never leads back to where it started. A tree has no cycles, so the cycle leak above cannot happen, and destroying any object destroys exactly what is under it.
  2. A pointer may point up the tree, or to anything that its own owner keeps alive longer. A paragraph’s section outlives the paragraph, because it owns it. That is why the back-reference is safe as a pointer.
  3. A pointer that would point across the tree, to something that can be destroyed first, must either be kept in step by the code that destroys the target, or be replaced by an id. The index is kept in step: the document is the only code that deletes paragraphs, and it removes the index entry in the same function. Comments and links use ids, because nobody would remember to clear them.
The document's ownership graph: solid arrows own and form a tree, dashed arrows point without owning, and lines ending in a circle name a paragraph by id
Text description of the diagram

An ownership graph of a document with two sections, Introduction and Design. Owning edges, which form a tree: Document owns both sections, one comment, and its index. Introduction owns paragraphs 1.1 and 1.2; Design owns paragraph 2.1. Pointer edges, which do not own: each paragraph points back to the section that owns it, and the index points to every paragraph. Id edges: paragraph 2.1 links to paragraph 1.1 by id, and the comment is on paragraph 1.2 by id. Every pointer either points up the tree to an owner, or is removed by the Document before its target is destroyed. Every reference across the tree is an id.

Diagram source (Mermaid)
flowchart TB
Doc["Document"]
S1["Section: Introduction"]
S2["Section: Design"]
P1["Paragraph 1.1"]
P2["Paragraph 1.2"]
P3["Paragraph 2.1"]
C1["Comment"]
Idx["index_<br/>map from id to Paragraph pointer"]
Doc -->|owns| S1
Doc -->|owns| S2
Doc -->|owns| C1
Doc -->|owns| Idx
S1 -->|owns| P1
S1 -->|owns| P2
S2 -->|owns| P3
P1 -.->|"points to (parent)"| S1
P2 -.->|"points to (parent)"| S1
P3 -.->|"points to (parent)"| S2
Idx -.->|points to| P1
Idx -.->|points to| P2
Idx -.->|points to| P3
P3 --o|"names by id: link"| P1
C1 --o|"names by id: on"| P2

Drawing the graph before writing code is the cheap part. Each “points to” arrow is a promise someone has to keep; the rest of the page shows how the code keeps it.

The owning edges are std::unique_ptr members. A paragraph points back at its section with a plain pointer:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

document.hpp
// One paragraph of text. It is always created, owned, and destroyed on
// the heap through a Section's unique_ptr, so its address never changes
// while it exists. Outside code can only read it; every change goes
// through Document.
class Paragraph {
public:
// "= delete" forbids copying. With the copy constructor deleted, the
// compiler does not declare a move constructor either, so a Paragraph
// cannot be copied or moved at all: the one object stays where it is.
Paragraph(const Paragraph&) = delete;
Paragraph& operator=(const Paragraph&) = delete;
ParagraphId id() const noexcept { return id_; }
const std::string& text() const noexcept { return text_; }
// The section this paragraph is in. Never null: only Document creates
// and moves paragraphs, and it keeps this pointer up to date.
const Section& section() const noexcept { return *section_; }
// The paragraph this one links to, by id, or std::nullopt if none.
std::optional<ParagraphId> link() const noexcept { return link_; }
private:
// `friend` lets Document use the private parts below, including this
// private constructor; no other code can create a Paragraph.
friend class Document;
Paragraph(ParagraphId id, std::string text, Section& section);
ParagraphId id_;
std::string text_;
Section* section_; // refers to the owner; does not own it
std::optional<ParagraphId> link_; // refers to another paragraph by id
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

document.hpp
// A titled list of paragraphs, in order. It owns its paragraphs, and like
// Paragraph it cannot be copied or moved and only Document can change it.
class Section {
public:
Section(const Section&) = delete;
Section& operator=(const Section&) = delete;
const std::string& title() const noexcept { return title_; }
std::size_t paragraph_count() const noexcept { return paragraphs_.size(); }
// at() throws std::out_of_range for a bad index; the * then turns the
// unique_ptr into a reference to the Paragraph it owns (a borrow).
const Paragraph& paragraph(std::size_t index) const { return *paragraphs_.at(index); }
private:
friend class Document;
// The title is taken by value and moved in: at most one copy is made,
// and none when the caller passes a temporary or std::move.
explicit Section(std::string title) : title_(std::move(title)) {}
std::string title_;
// Owns, in order. Each paragraph is a separate heap object; when the
// vector grows or an element is erased, only these pointers move.
std::vector<std::unique_ptr<Paragraph>> paragraphs_; // owns, in order
};

Why each choice:

  • Children live on the heap, one unique_ptr each. A vector of unique_ptr can grow, shrink, and reorder without moving the objects themselves; only the pointers inside the vector move. So Paragraph::section_ and every index entry stay valid when a section gains a paragraph, and Document keeps its sections the same way, so a section’s address never changes when another section is added or deleted. This is the fix for “parents that move”. A vector of values would be cheaper, and is the better choice when nothing points at the elements.
  • Neither class can be copied or moved. Deleting the copy constructor also stops the compiler from declaring a move constructor. So nobody can make a second Paragraph or Section from an existing one, and neither can be stored by value in a container that moves its elements; the only way to have one is the object Document created, at the address it was created at. A copy of a paragraph would be a second object with the same id and a pointer to a section it is not in.
  • The back-pointer is a raw pointer, and it is never null. It does not own (rule 2), so a smart pointer would say the wrong thing. section() returns a reference, so callers do not have to check for null. A Section& member could not be made to refer to a different section, so D2 would be impossible.
  • Only Document can change any of it. The constructors and the data that holds the graph together are private, and Document is a friend of both classes. A friend is usually a smell; here it is the point. The three classes are one unit with one set of invariants (every paragraph is owned by exactly one section, its section_ names that section, the index has exactly the live paragraphs), and only one class can be trusted to keep them. Code outside reads through const functions and cannot break them.

D2 moves a paragraph to another section. In the graph, one owning edge moves and one back-pointer changes; the paragraph itself stays where it is in memory:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

document.cpp
// Moves a paragraph to the end of another section. The Paragraph object
// stays at the same address; only the unique_ptr that owns it moves from
// one vector to the other, and its back-pointer is updated. All checks
// come first, so a refused move changes nothing.
void Document::move_paragraph(ParagraphId id, std::size_t to_section) {
Paragraph& paragraph = existing(id); // throws if the id is unknown
Section& to = *sections_.at(to_section); // throws if the section is not there
Section& from = *paragraph.section_;
// Comparing addresses (&from, &to) asks "the very same section?".
if (&from == &to) throw std::invalid_argument("the paragraph is already in that section");
// Find the slot in `from` whose unique_ptr owns this paragraph. The
// lambda compares each owned address with the paragraph's. It always
// finds one, because section_ says the paragraph is in `from`.
const auto slot = std::find_if(from.paragraphs_.begin(), from.paragraphs_.end(),
[&](const auto& owned) { return owned.get() == &paragraph; });
// If this throws (no memory), nothing has changed: a unique_ptr moves
// without throwing, so push_back either succeeds or has no effect.
// *slot is the unique_ptr in `from`; std::move hands its ownership to
// the new element at the end of `to`, and leaves *slot empty (null).
to.paragraphs_.push_back(std::move(*slot));
// `slot` is still valid: the push_back changed a different vector.
// erase removes the empty slot and shifts the later pointers down one.
from.paragraphs_.erase(slot); // only the empty unique_ptr is left there
paragraph.section_ = &to; // the object did not move; its owner did
}
How this code works: move_paragraph, step by step

The demo program moves goal, the paragraph “What the tool must do.”, from Introduction to Design. Its id is 1, because it was the first paragraph added; scope is 2 and classes is 3. Call the three heap objects P1, P2, and P3.

Step Introduction’s paragraphs_ Design’s paragraphs_ P1’s section_
before the call P1, P2 P3 Introduction
checks pass; slot points at P1’s slot P1, P2 P3 Introduction
after push_back(std::move(*slot)) (empty), P2 P3, P1 Introduction
after erase(slot) P2 P3, P1 Introduction
after section_ = &to P2 P3, P1 Design
  1. Checks first. existing finds P1 through the index, or throws for an unknown id. at throws for a section that does not exist. The if refuses a move into the section the paragraph is already in. Nothing has changed yet, so a refusal leaves the document as it was.
  2. Find the owning slot. find_if walks Introduction’s vector and stops at the unique_ptr whose address is P1’s.
  3. Hand over ownership. std::move(*slot) lets the new element at the end of Design’s vector take P1 over. The slot in Introduction still exists, but now holds a null unique_ptr. P1 itself has not moved: it is the same object at the same address.
  4. Tidy up. erase removes the empty slot, and P2 shifts down from position 1 to position 0. Only the pointer moved; P2 did not.
  5. Fix the back-pointer. P1’s section_ now names Design.

The index never changes: it still maps id 1 to P1’s address, which is still right. That is why find(goal) after the move returns the same pointer as before, and the demo prints “same object”.

  • The owning unique_ptr is moved from one vector to the other. The paragraph’s address does not change, so the index entry still points at the right object, with nothing to update.
  • The back-pointer is updated in the same function, after the last step that can fail. Before the last line runs, the paragraph is owned by to but still points at from; only the erase of an empty unique_ptr runs in between, so no other code can see that.
  • The order matters for failure. If the push_back cannot get memory, it throws and changes nothing, because moving a unique_ptr never throws. The paragraph is still in from, and from is changed only after to has accepted it. Doing it the other way round, erase first, would lose the paragraph if the push_back then failed. Exception safety and failure atomicity treats this ordering in detail.

Links (D4) and comments (D5) refer to paragraphs that can be deleted at any time. They use an id:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

document.hpp
// Names a paragraph without pointing at it. An id stays meaningful after
// the paragraph is deleted: looking it up then finds nothing.
// It is a struct around the number, not a bare std::uint64_t, so that a
// paragraph id cannot be mixed up with a count or an index by mistake.
struct ParagraphId {
std::uint64_t value = 0; // 0 is never issued: the Document starts at 1
// "= default" asks the compiler to write ==, !=, <, and the rest by
// comparing `value`. The < is what lets an id be a std::map key.
auto operator<=>(const ParagraphId&) const = default;
};

An id can never dangle. It is a number; the worst it can do is name something that no longer exists, and the owner can answer that question. An id means something only to the Document that issued it: every document starts counting at 1, so an id taken from one document and looked up in another silently names an unrelated paragraph (the last item under “When the requirements change” comes back to this). The Document owns everything and holds the one map from ids to paragraphs:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

document.hpp
// Owns every section, paragraph, and comment. All changes go through it.
//
// References returned by section(), Section::paragraph(), and find(), and
// any reference obtained through them (title(), text(), section()), are
// borrowed: they stay valid until the next call to a non-const member
// function of this Document. Moving the Document keeps them valid;
// destroying it or assigning to it ends them. Keep a ParagraphId to refer
// to a paragraph for longer.
class Document {
public:
Document() = default;
// No copying: a copy would have to rebuild every back-pointer and index
// entry to point into the copy, and this class does not offer that.
Document(const Document&) = delete;
Document& operator=(const Document&) = delete;
// Moving is allowed and cheap: the vectors and map hand over their
// heap storage, and the sections and paragraphs stay where they are.
Document(Document&&) = default;
Document& operator=(Document&&) = default;
// The changes. Sections are named by position (0 is the first);
// paragraphs by id. A bad position throws std::out_of_range; an id
// with no live paragraph throws std::invalid_argument.
void add_section(std::string title);
// Adds at the end of the section, and returns the new paragraph's id.
ParagraphId add_paragraph(std::size_t section, std::string text);
// Moves to the end of another section; the same section is refused.
void move_paragraph(ParagraphId id, std::size_t to_section);
void remove_paragraph(ParagraphId id);
// Removes the section and every paragraph in it.
void remove_section(std::size_t section);
// Both must exist now, and differ; the target may be deleted later.
void link(ParagraphId from, ParagraphId to);
void comment(ParagraphId on, std::string text);
std::size_t section_count() const noexcept { return sections_.size(); }
const Section& section(std::size_t index) const { return *sections_.at(index); }
// The live paragraph with this id, or nullptr if there is none.
const Paragraph* find(ParagraphId id) const noexcept;
// "2.1" for the first paragraph of the second section; empty if the
// paragraph has been deleted.
std::optional<std::string> number(ParagraphId id) const;
std::string render() const;
private:
// Like find(), but for changes: throws std::invalid_argument instead
// of returning null, and gives a non-const paragraph.
Paragraph& existing(ParagraphId id);
std::vector<std::unique_ptr<Section>> sections_; // owns, in order
// Every live paragraph's id and address, so find() need not search
// every section. Raw pointers that do not own; Document removes an
// entry before it destroys the paragraph.
std::map<ParagraphId, Paragraph*> index_; // refers; kept in step
std::vector<Comment> comments_; // owns (values)
std::uint64_t next_id_ = 1; // only counts up, so an id is never reused
};

Turning an id into an object goes through the owner, which either finds it or does not:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

document.cpp
// The paragraph's current number, such as "2.1", worked out from where it
// is in the tree right now. std::nullopt if the paragraph was deleted.
// Nothing is stored, so the number can never be out of date.
std::optional<std::string> Document::number(ParagraphId id) const {
// id -> paragraph, through the index.
const Paragraph* paragraph = find(id);
if (paragraph == nullptr) return std::nullopt; // deleted: no number
// paragraph -> its section, through the back-pointer.
const Section& section = paragraph->section();
// Where is that section among the sections, and where is the paragraph
// in its section? Each find_if compares addresses, as in
// move_paragraph. Both always succeed for a live paragraph.
const auto in_document = std::find_if(sections_.begin(), sections_.end(),
[&](const auto& s) { return s.get() == &section; });
const auto in_section = std::find_if(section.paragraphs_.begin(), section.paragraphs_.end(),
[&](const auto& p) { return p.get() == paragraph; });
// std::distance from begin() to the iterator is the 0-based position;
// + 1 turns it into the 1-based number a reader expects.
return std::to_string(std::distance(sections_.begin(), in_document) + 1) + "." +
std::to_string(std::distance(section.paragraphs_.begin(), in_section) + 1);
}
How this code works: Computing a number: why the link says see 2.2

After the move above, render reaches the link in “The main classes.” and calls number with goal’s id, 1:

  1. find(1) looks the id up in the index and gets P1’s address. If the paragraph had been deleted, find would return null and number would return std::nullopt, which render shows as “a deleted paragraph”.
  2. paragraph->section() follows the back-pointer to Design.
  3. The first find_if looks for Design among the sections. It is the second one, so std::distance from begin() is 1.
  4. The second find_if looks for P1 among Design’s paragraphs, which are now P3, P1. It is the second one, so the distance is 1 again.
  5. Both get + 1, and the result is "2.2".

Before the move, the same calls gave section distance 0 and paragraph distance 0, so "1.1". Nothing about the link changed: it still holds id 1. Only the tree around P1 changed, and number reads the tree each time.

number follows the index to the paragraph, follows the back-pointer to its section, then counts positions. Because positions are computed each time from the tree, the number shown for a link or a comment is always current after a move (D4), and a deleted paragraph simply has no number.

Ids have other uses that a pointer lacks. An id can be saved to a file and read back; a pointer means nothing in another run. It can be sent to another program or shown to a user. It can be compared after the object is gone, for example to show “you deleted this paragraph”. The cost is a lookup each time, here a std::map search plus, for number, a scan of the sections and of one section’s paragraphs to find positions, and the need for an owner that can do the lookup. render pays that for every link and comment, which is fine for documents of a few thousand paragraphs.

Ids are only safe if they are never reused. If a new paragraph got the id of a deleted one, every old comment on the deleted paragraph would silently move to the new one. next_id_ only counts up, and a test checks it.

The index is a map of pointers, and pointers can dangle. It is safe because of one rule: the code that destroys an object first removes every pointer to it. That is only possible when every such pointer is known, which is why the index is private to Document, the only code that deletes paragraphs:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

document.cpp
// Deletes one paragraph. Comments and links that name it by id are left
// alone: from now on, looking the id up finds nothing.
void Document::remove_paragraph(ParagraphId id) {
Paragraph& paragraph = existing(id); // throws std::invalid_argument if already gone
// The owning vector of the paragraph's section, reached through the
// back-pointer, and the slot in it that owns this paragraph.
auto& owned = paragraph.section_->paragraphs_;
const auto slot = std::find_if(owned.begin(), owned.end(),
[&](const auto& p) { return p.get() == &paragraph; });
index_.erase(id); // first remove the pointer that refers to it,
// Erasing the unique_ptr deletes the Paragraph. After this line the
// reference `paragraph` dangles, so nothing below may use it.
owned.erase(slot); // then destroy it, through its owner
}
// Deletes a section and, with it, all of its paragraphs. Every one of
// their index entries is removed first; otherwise the index would keep
// pointers to paragraphs that no longer exist.
void Document::remove_section(std::size_t section) {
if (section >= sections_.size()) throw std::out_of_range("no such section");
// An iterator to the section's slot: begin() plus the position.
// Iterators step by a signed distance and `section` is unsigned, so the
// cast makes that conversion explicit; the check above makes it safe.
const auto slot = sections_.begin() + static_cast<std::ptrdiff_t>(section);
// (*slot) is the section's unique_ptr; -> reaches the Section itself.
for (const auto& paragraph : (*slot)->paragraphs_) index_.erase(paragraph->id_);
// The section's unique_ptr deletes the Section, whose vector of
// unique_ptrs deletes each paragraph in turn. Later sections shift
// down one position, so their numbers change, but not their addresses.
sections_.erase(slot); // destroys the section and every paragraph in it
}
  • remove_paragraph removes the index entry, then lets the owning unique_ptr destroy the paragraph. Neither step can throw, so the two cannot get out of step.
  • remove_section destroys a whole sub-tree at once. It first removes the index entry for every paragraph in that section, because sections_.erase will destroy them all. Forgetting that loop is the classic bug of an index: every lookup of those ids would return a pointer to freed memory.
  • Comments and links are not touched. They name the paragraph by id, so after the deletion they find nothing and say so, which is what D5 asks for.

Adding is the reverse: the index entry and the owning pointer must both be added, or neither:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

document.cpp
// Creates a paragraph at the end of a section. Two things must change
// together: the index gets an entry, and the section gets the owning
// pointer. If either step fails, the document is left exactly as it was
// and the exception reaches the caller.
ParagraphId Document::add_paragraph(std::size_t section, std::string text) {
Section& owner = *sections_.at(section); // throws std::out_of_range for a bad section
const ParagraphId id{next_id_};
// `new` is used, not std::make_unique, because the constructor is
// private: make_unique could not call it, but Document, a friend, can.
// The unique_ptr owns the paragraph from this line on, so if anything
// below throws, the paragraph is deleted automatically.
std::unique_ptr<Paragraph> paragraph(new Paragraph(id, std::move(text), owner));
// Step 1: emplace adds (id, address) to the map and returns a pair; its
// .first is an iterator to the new entry, kept so it can be undone.
// get() reads the address without giving up ownership.
const auto entry = index_.emplace(id, paragraph.get()).first;
try {
// Step 2: hand ownership to the section. On success the vector's new
// element owns the object and `paragraph` is left empty. If it
// throws (no memory), push_back has no effect, so `paragraph` still
// owns the object and deletes it when the exception leaves.
owner.paragraphs_.push_back(std::move(paragraph));
} catch (...) {
index_.erase(entry); // undo the first step, so nothing changed
throw; // rethrow the same exception to the caller
}
// Only now, after both steps worked, is the id used up. A failed add
// leaves next_id_ alone, which is safe because that id was never seen.
++next_id_;
return id;
}

If adding the index entry throws, nothing has changed yet. If the push_back throws, the catch takes the entry out again before the exception continues, and the new paragraph is destroyed by its unique_ptr. Either way the index never holds a pointer to a paragraph that is not in the tree.

Borrowing: how long a returned reference is valid

Section titled “Borrowing: how long a returned reference is valid”

find, section, and Section::paragraph return pointers and references into the document. The caller does not own them; it borrows them. A borrowed reference is only useful if the rules for how long it lasts are written down. Document states them in its header: a borrowed reference stays valid until the next call to a non-const member function of the document. To refer to a paragraph for longer, keep its ParagraphId.

The rule is deliberately stricter than what the code needs today. After move_paragraph, a borrowed const Paragraph* still points at the right object, and the tests check exactly that. But the rule lets the document change how it stores paragraphs later, and it is easy to follow: borrow, use, drop, then change.

Breaking the rule is undefined behavior. This keeps a borrowed pointer across a deletion:

Under both compilers, AddressSanitizer stopped the program with a heap-use-after-free report on the last line. Without a sanitizer, the same program may print the old value, print garbage, or crash; the behavior is undefined, so no result is reliable. This is why the example’s tests also run under the sanitizer build.

Three habits follow from the rule:

  • Do not store a borrowed reference in an object that lives longer than the current function. Store the id.
  • Do not change the document while iterating over it. Collect the ids of what to change first, then change it.
  • Prefer functions that return values (number returns a std::string) when the caller needs a result after the next change.

Each edge that does not own has several possible C++ types. The question is always the same: can the target be destroyed while the source still exists, and who notices?

Reference Use when What goes wrong if misused Cost
reference or raw pointer the target outlives the source (points up the tree, or at something the owner keeps) dangles silently when the target goes first none
pointer kept in step by owner the owner of the target knows every such pointer (a private index) one forgotten update dangles the owner’s code must update it on every change
id plus a lookup the target may go first, and the source should find out a reused id names the wrong object a lookup each time; needs an owner to ask
std::weak_ptr the target is already owned through std::shared_ptr for a real reason lock() keeps the target alive while the result is held a control block and atomic counts
notification (Observer) the source must react at once when the target goes, not on its next use a missed unsubscribe dangles; Observer shows this a list of listeners and calls on every change
std::shared_ptr (owning) ownership really is shared: several owners, and which one finishes last is not known in advance cycles leak; lifetime becomes hard to reason about a control block and atomic counts

std::weak_ptr is the tempting alternative to the id here: make the sections own paragraphs through std::shared_ptr, and let comments hold std::weak_ptr<Paragraph>.

An owning cycle is a set of objects that own each other, directly or through others, so that none of them is ever destroyed. With std::shared_ptr it happens as soon as two objects hold each other; Smart pointers shows a two-object cycle and how std::weak_ptr breaks it. With std::unique_ptr it takes moving an object into something it already owns, which one check rules out: never add a child to one of its own descendants. Composite refuses to put a folder inside itself for this reason. The document cannot have the problem at all, because sections cannot contain sections.

A cycle that includes a non-owning edge is fine. Paragraph → section → paragraph is a cycle in the drawing, but only one of the two edges owns, so destruction has an order: the section first destroys its paragraphs, and the paragraphs never use their back-pointer while being destroyed.

Some data really is a graph: tasks that depend on other tasks, a road map, people who follow each other. Forcing it into a tree of owners would be wrong. The usual design is a central store, sometimes called an arena: one object owns all the nodes, and the edges between nodes are ids. (Arena also often means a memory allocator that frees everything at once; here it only means the single owner.)

The owning graph is again a tree, one level deep: the store owns every node. The real graph lives in the ids. remove decides what an edge to a removed node means, the same question D5 answered for comments.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// Builds a two-section document, then shows the three things the page is
// about: the starting tree, a move (same object, new number), and a
// deletion (links and comments report it instead of dangling).
int main() {
doc::Document document;
document.add_section("Introduction"); // section 0, shown as 1
document.add_section("Design"); // section 1, shown as 2
// The program keeps ids, not pointers, to refer to paragraphs later.
const doc::ParagraphId goal = document.add_paragraph(0, "What the tool must do."); // 1.1
const doc::ParagraphId scope = document.add_paragraph(0, "What it will not do."); // 1.2
const doc::ParagraphId classes = document.add_paragraph(1, "The main classes."); // 2.1
document.link(classes, goal); // 2.1 says "see" whatever number goal has
document.comment(scope, "Too vague; list the cases.");
document.comment(goal, "Agreed.");
std::cout << document.render() << '\n';
// The paragraph keeps its id and its address; its number changes.
// `before` is kept across a change only to compare addresses, which
// the borrowing rule would not allow in ordinary code.
const doc::Paragraph* before = document.find(goal);
document.move_paragraph(goal, 1);
// find(goal) is called again after the change, so it is a fresh borrow.
std::cout << "moved: " << (document.find(goal) == before ? "same object" : "new object")
<< ", now in " << document.find(goal)->section().title() << '\n';
std::cout << document.render() << '\n';
// Comments and links refer by id, so deleting a paragraph cannot leave
// them pointing at freed memory. They report the deletion instead.
document.remove_paragraph(goal);
std::cout << "deleted: find returns " << (document.find(goal) == nullptr ? "null" : "a paragraph")
<< '\n';
std::cout << document.render();
}
Expected output
1 Introduction
1.1 What the tool must do.
1.2 What it will not do.
2 Design
2.1 The main classes. (see 1.1)
comment on 1.2: Too vague; list the cases.
comment on 1.1: Agreed.
moved: same object, now in Design
1 Introduction
1.1 What it will not do.
2 Design
2.1 The main classes. (see 2.2)
2.2 What the tool must do.
comment on 1.1: Too vague; list the cases.
comment on 2.2: Agreed.
deleted: find returns null
1 Introduction
1.1 What it will not do.
2 Design
2.1 The main classes. (see a deleted paragraph)
comment on 1.1: Too vague; list the cases.
comment on a deleted paragraph: Agreed.

Reading the output:

  • The first listing shows the starting tree: the link in 2.1 shows “see 1.1”, and both comments show their paragraph’s number.
  • After the move, find returns the same address as before, and the back-pointer answers “Design”. The link now shows “see 2.2” and the comment “on 2.2”, because numbers are computed from the tree.
  • After the deletion, find returns null. The link and the comment are still there and say “a deleted paragraph” instead of pointing at freed memory.

The tests check the tree, then the references:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_document.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false; LLD_CHECK_EQ(actual, expected) does the same
// for an equality and prints both values when they differ; and
// LLD_CHECK_THROWS(expression, type) fails unless the expression throws
// that type of exception. They come from the site's small test header,
// lld_test.hpp.
//
// Every test starts from two_sections(), a helper earlier in this file
// that returns a Document with sections "A" (position 0) and "B" (1).
// Proves: numbers come from section position and paragraph position,
// both counted from 1.
LLD_TEST(paragraphs_are_numbered_by_section_and_position) {
Document document = two_sections();
const ParagraphId first = document.add_paragraph(0, "one");
const ParagraphId second = document.add_paragraph(0, "two");
const ParagraphId third = document.add_paragraph(1, "three");
// number() returns an optional, so it is compared with an optional
// holding the expected text.
LLD_CHECK(document.number(first) == std::optional<std::string>("1.1"));
LLD_CHECK(document.number(second) == std::optional<std::string>("1.2"));
LLD_CHECK(document.number(third) == std::optional<std::string>("2.1"));
}
// Proves D2: after a move, find() returns the same address as before,
// the back-pointer names the new section, the old section is empty, and
// the number has changed to match the new place.
LLD_TEST(a_moved_paragraph_is_the_same_object_with_a_new_section) {
Document document = two_sections();
const ParagraphId id = document.add_paragraph(0, "text");
// `before` is kept across a change only to compare addresses; it is
// never used to read the paragraph after the move.
const doc::Paragraph* before = document.find(id);
document.move_paragraph(id, 1);
LLD_CHECK(document.find(id) == before);
LLD_CHECK_EQ(document.find(id)->section().title(), std::string("B"));
LLD_CHECK_EQ(document.section(0).paragraph_count(), std::size_t{0});
LLD_CHECK(document.number(id) == std::optional<std::string>("2.1"));
}
// Proves: moving into the section it is already in throws
// invalid_argument, a section that does not exist throws out_of_range,
// and after both refusals the paragraph is still 1.1.
LLD_TEST(moving_into_its_own_section_is_refused_and_changes_nothing) {
Document document = two_sections();
const ParagraphId id = document.add_paragraph(0, "text");
LLD_CHECK_THROWS(document.move_paragraph(id, 0), std::invalid_argument);
LLD_CHECK_THROWS(document.move_paragraph(id, 5), std::out_of_range);
LLD_CHECK(document.number(id) == std::optional<std::string>("1.1"));
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_document.cpp
// Proves: once deleted, an id finds nothing, has no number, cannot be
// deleted twice, and is not handed out again to the next new paragraph.
LLD_TEST(a_deleted_paragraph_cannot_be_found_and_its_id_is_not_reused) {
Document document = two_sections();
const ParagraphId id = document.add_paragraph(0, "text");
document.remove_paragraph(id);
LLD_CHECK(document.find(id) == nullptr);
LLD_CHECK(!document.number(id).has_value());
LLD_CHECK_THROWS(document.remove_paragraph(id), std::invalid_argument);
LLD_CHECK(document.add_paragraph(0, "new") != id);
}
// Proves D4 and D5: a link and a comment on a deleted paragraph stay in
// the document and render as "a deleted paragraph". After the deletion,
// section A is empty and "source" is still 2.1.
LLD_TEST(links_and_comments_report_a_deleted_target) {
Document document = two_sections();
const ParagraphId target = document.add_paragraph(0, "target");
const ParagraphId source = document.add_paragraph(1, "source");
document.link(source, target);
document.comment(target, "note");
document.remove_paragraph(target);
LLD_CHECK_EQ(document.render(), std::string("1 A\n"
"2 B\n"
" 2.1 source (see a deleted paragraph)\n"
"comment on a deleted paragraph: note\n"));
}
// Proves: deleting a section removes its paragraphs' index entries (so
// find() returns null, not a dangling pointer), and the next section moves
// up to position 0, so "kept" is now 1.1. Only one section is left, so
// position 1 no longer exists.
LLD_TEST(removing_a_section_removes_its_paragraphs_from_the_index) {
Document document = two_sections();
const ParagraphId gone = document.add_paragraph(0, "gone");
const ParagraphId kept = document.add_paragraph(1, "kept");
document.remove_section(0);
LLD_CHECK(document.find(gone) == nullptr);
LLD_CHECK(document.number(kept) == std::optional<std::string>("1.1"));
LLD_CHECK_THROWS(document.remove_section(1), std::out_of_range);
}
// Proves: a link to an id that was never issued (99), a link from a
// paragraph to itself, and a comment on an unknown id are all refused,
// and the refused links leave the paragraph with no link.
LLD_TEST(links_and_comments_need_an_existing_paragraph) {
Document document = two_sections();
const ParagraphId id = document.add_paragraph(0, "text");
LLD_CHECK_THROWS(document.link(id, ParagraphId{99}), std::invalid_argument);
LLD_CHECK_THROWS(document.link(id, id), std::invalid_argument);
LLD_CHECK_THROWS(document.comment(ParagraphId{99}, "lost"), std::invalid_argument);
LLD_CHECK(!document.find(id)->link().has_value());
}
// Proves the header's promise: moving a Document hands over its storage
// without moving any section or paragraph, so the address found before
// the move is still the paragraph's address in `moved`.
LLD_TEST(moving_the_document_keeps_every_reference_valid) {
Document document = two_sections();
const ParagraphId id = document.add_paragraph(1, "text");
const doc::Paragraph* before = document.find(id);
// After this line, `document` is only fit to be destroyed or assigned
// to; the test does not use it again.
Document moved = std::move(document);
LLD_CHECK(moved.find(id) == before);
LLD_CHECK_EQ(moved.find(id)->section().title(), std::string("B"));
}
  • The move tests compare addresses before and after, which is the property the index relies on. They keep a pointer across a change only to compare it, a deliberate look inside that the borrowing rule does not promise to callers.
  • The deletion tests check every kind of edge to a deleted paragraph: the index (find returns null), ids (not reused), links, and comments. removing_a_section_removes_its_paragraphs_from_the_index catches the missing loop in remove_section.
  • The document move test shows that moving the Document object is safe: nothing points into the Document itself, only into objects on the heap that it owns.
  • The tests run under AddressSanitizer in the sanitizer build. A test that passes in a normal build can still be reading freed memory; the sanitizer usually turns that into a failure. It can miss reads made inside library code that was not built with it, as exercise A shows.

What is not tested: the failure paths in add_paragraph and move_paragraph, because making push_back run out of memory needs a custom allocator or a test hook. The exception-safety page shows a way to inject such failures.

class doc::Document

owns everything; the only class that changes the graph

Data members

  • std::vector<std::unique_ptr<Section>> sections_; owns
  • std::map<ParagraphId, Paragraph*> index_; points to; kept in step
  • std::vector<Comment> comments_; owns, values

Member functions

  • void add_section(std::string title);
  • ParagraphId add_paragraph(std::size_t section, std::string text);
  • void move_paragraph(ParagraphId id, std::size_t to_section);
  • void remove_paragraph(ParagraphId id);
  • void remove_section(std::size_t section);
  • const Paragraph* find(ParagraphId id) const noexcept; borrowed
  • std::optional<std::string> number(ParagraphId id) const;

class doc::Section

cannot be copied or moved

Data members

  • std::vector<std::unique_ptr<Paragraph>> paragraphs_; owns

Member functions

  • const Paragraph& paragraph(std::size_t index) const; borrowed

class doc::Paragraph

cannot be copied or moved

Data members

  • Section* section_; points to the owner

Member functions

  • const Section& section() const noexcept; the parent
  • std::optional<ParagraphId> link() const noexcept; by id

class doc::ParagraphId

a value; never reused

Member functions

  • std::uint64_t value;
The document model; members summarized

Use the three-edge graph whenever objects are created and destroyed at different times and refer to each other: documents, scenes, user interfaces, caches, game worlds, simulation models. Draw it before choosing types.

  • Ownership is a tree most of the time. Look for the tree first and use std::unique_ptr or values for its edges.
  • Pointers up the tree are cheap and safe, if one class keeps them correct.
  • Ids across the tree cost a lookup and remove a whole class of bugs. They are the default for anything that can outlive its target, be saved, or be shown to a user.

It is more than needed when every object lives for the whole run, as in the composition root, or when the data is plain values with no references between them. A std::vector<Paragraph> of values and numbers computed from positions would be enough for a document with no links, no comments, and no outside code holding paragraphs.

  • Using std::shared_ptr because ownership is “unclear”. It hides the decision instead of making it, and back-references through it become cycles. Decide the owner first.
  • Pointers to elements of a vector of values. Growth, insertion, and erasure move the elements. Use std::unique_ptr elements, a container whose elements stay put (such as std::list, or std::map for its values), or ids.
  • Raw pointers across the tree with no one to clear them. Comments, links, selections, and caches that point at objects someone else deletes. Use ids, or keep the pointers private to the owner.
  • Letting outside code change the parent. If anyone can set section_, nobody can promise it is right. Keep graph changes in one class.
  • Reusing ids. A freed id that comes back makes old references point at the wrong object without any error.
  • Undocumented borrows. A function that returns a reference must say how long it is valid, in its header.
  • “Undo a deletion.” With ids, undo can put the paragraph back with the same id, and every comment and link finds it again. With pointers, they would already be dangling. The deleted paragraph would be kept by the undo history (Memento or Command), which becomes a second owner in time: the document owns live paragraphs, the history owns deleted ones.
  • “Copy a paragraph to another document.” The copy is a new object with a new id in the other document. Its link names an id in the first document, which means nothing in the second, so the copy must decide: drop the link, or keep it as text.
  • “Two documents share a style sheet.” Here ownership really is shared, and the style sheet does not change while used: std::shared_ptr<const StyleSheet> fits.
  • “Several threads edit the document.” The borrowing rule becomes much harder to keep, because another thread may make “the next change” at any moment. That needs locking or a single owning thread, covered on the planned pages on thread safety and synchronization.

Exercise: Find a lifetime bug

Each snippet uses the example’s doc::Document, which has two sections; section 0 holds several paragraphs, including two empty ones in a row. For each, say whether it has a lifetime bug, whether it breaks the borrowing rule but happens to work with today’s code, or whether it is correct. Fix each one that is not correct.

These snippets, and the fix for C, were compiled against the example as a separate test file with GCC 11.4 and Clang 14 and run with AddressSanitizer; the answer says what happened.

// A: take a reference to the first section's title, delete that section,
// then print the title.
const std::string& title = document.section(0).title();
document.remove_section(0);
std::cout << title << '\n';
// B: take a reference to the first paragraph, move it to section 1, then
// print its text through the same reference.
const doc::Paragraph& first = document.section(0).paragraph(0);
document.move_paragraph(first.id(), 1);
std::cout << first.text() << '\n';
// C: delete every empty paragraph in section 0
// Walks the section by position, and deletes inside the loop.
const doc::Section& section = document.section(0);
for (std::size_t i = 0; i < section.paragraph_count(); ++i) {
if (section.paragraph(i).text().empty()) {
document.remove_paragraph(section.paragraph(i).id());
}
}
// D: remember the first paragraph by id in a small struct, delete its
// section, then look the id up again.
struct Selection {
doc::ParagraphId paragraph;
};
Selection selected{document.section(0).paragraph(0).id()};
document.remove_section(0);
// The `if` declares `p` and tests it: the body runs only if find()
// returned a non-null pointer.
if (const doc::Paragraph* p = document.find(selected.paragraph)) {
std::cout << p->text() << '\n';
}
Show the explained answer
  • A is a lifetime bug. title refers to a string inside the section, and remove_section destroys the section. Reading title is undefined behavior. When we ran it, the program stopped under AddressSanitizer with both compilers, but with a report of a bad memory read (SEGV), not a use-after-free: the read happens inside the standard library’s compiled std::string code, which is not instrumented, so the sanitizer could not see that the memory was freed, and the crash depended on what the freed memory held. Fix: copy it first, const std::string title = document.section(0).title();.

  • B breaks the rule but works today. The move does not change the paragraph’s address, so first still refers to the right object. But the header says a borrow ends at the next change, and a later version that stores paragraphs differently would turn this into a bug with no compile error. Fix: keep the id and look it up again, const doc::ParagraphId id = first.id(); before the move, then document.find(id)->text() after it.

  • C has two problems. It changes the document while holding a borrow (section), which breaks the rule. It also skips a paragraph: after removing the paragraph at i, the next one moves down to i, and ++i passes over it. Two empty paragraphs in a row leave the second, which is what happened when we ran it. Fix both by collecting first, then changing:

    // Pass 1 only reads: it borrows the section and collects ids, which stay
    // meaningful after any change.
    std::vector<doc::ParagraphId> empty;
    const doc::Section& section = document.section(0);
    for (std::size_t i = 0; i < section.paragraph_count(); ++i) {
    if (section.paragraph(i).text().empty()) empty.push_back(section.paragraph(i).id());
    }
    // Pass 2 only changes: it uses the ids, never `section`, so no borrow is
    // held across a removal, and no paragraph is skipped.
    for (const doc::ParagraphId id : empty) document.remove_paragraph(id);
  • D is correct. The selection stores an id, the borrow from paragraph(0) ends before the change, and find returns null for the deleted paragraph, which the if handles. This is the pattern to copy for anything that lives longer than one function.

  • An ownership graph has three kinds of edge: owns, points to, and names by id. Draw it from the requirements before choosing C++ types, asking for each edge which side is destroyed first.
  • Keep the owning edges a tree, using std::unique_ptr and values. A tree cannot have an ownership cycle.
  • A pointer up the tree, from child to parent, is safe because the parent outlives the child; one class must keep it correct when the child moves.
  • A reference across the tree should be an id that the owner looks up. Ids cannot dangle, can be saved, and must never be reused.
  • An index of pointers is safe only if the code that destroys an object removes its entry first, which needs the index to be private to that code.
  • Borrowed references need a written rule for how long they last. “Valid until the next change” is simple, and the fix for keeping something longer is to keep its id.
  • Data that really is a graph is usually best as a central store that owns every node, with ids for the edges.