References, pointers, and explicit ownership
What you will learn on this page
Section titled “What you will learn on this page”- The difference between an object’s owner and code that only uses it.
- How to read ownership from a function signature.
- When to use a reference and when a pointer for code that uses an object it does not own.
- How references and pointers dangle, and how design prevents it.
Owners and observers
Section titled “Owners and observers”Every object in a C++ program must be destroyed exactly once, at the right time. The code responsible for that is the object’s owner. Ownership is responsibility for ending an object’s lifetime and releasing what it holds.
Most code that uses an object does not own it. It reads or changes the object while someone else keeps it alive. This site calls such code an observer, or says it borrows the object. A program is easy to reason about when, for every object, you can answer two questions:
- Who owns it? There should be one clear answer, and usually it is “the enclosing object or scope” (a member, a local variable, an element of a container).
- Can every observer be sure the object is still alive while it uses it?
The previous lessons showed the simplest owners: a local variable is owned by its scope, and a data member by its enclosing object. This lesson is about the observers: references and pointers.
References and pointers in brief
Section titled “References and pointers in brief”A reference (Member&, const Member&) is another name for an existing
object. It must refer to an object from the moment it is created, and it cannot
later be made to refer to a different one.
A pointer (Member*, const Member*) is a value that holds an object’s
address. It can be null (written nullptr), meaning “no object”, and it can
be changed to point elsewhere. You reach the object with *ptr or ptr->member,
and you get an object’s address with &object.
IllustrativeA fragment for explanation; not compiled on its own.
Member ada{1, "Ada"};Member& ref = ada; // another name for adaMember* ptr = &ada; // the address of adaptr->name = "Ada L."; // changes ada, through the pointerMember* nobody = nullptr; // points to no objectNeither a reference nor a plain pointer (also called a raw pointer) owns anything. When a reference or pointer goes out of scope, nothing happens to the object it referred to. That is exactly what you want for observers, and exactly the problem if you try to use a raw pointer as an owner, which the next two lessons address.
Reading ownership from signatures
Section titled “Reading ownership from signatures”The convention this site follows, which is widespread in modern C++:
| You see | It means |
|---|---|
T (by value) |
The function or object has its own copy; it owns that copy. |
const T& |
Borrows for reading during the call. Never null. |
T& |
Borrows for changing during the call. Never null. |
const T* or T* |
Observes an object that may be absent (nullptr). Not owned. |
std::unique_ptr<T> |
Owns exclusively; passing one by value transfers ownership. |
std::shared_ptr<T> |
Shares ownership with other shared_ptrs. |
So raw pointers and references never own in well-designed modern C++. Owning is done by values, containers, and smart pointers (the RAII and smart pointer lessons). That rule is what makes ownership readable from the signature alone.
Here is a set of functions written to that convention:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Declarations only: the bodies are in directory.cpp. Read each// parameter type as a promise about ownership.//// Borrows for reading; the caller keeps ownership; never null.// Returns text such as "#2 Grace H.".std::string label(const Member& member);
// Borrows for modifying; never null. Takes the new name by value (a sink).void rename(Member& member, std::string new_name);
// Accepts "maybe a member": the pointer may be null. Does not keep it.// Returns the member's label, or "guest" when given nullptr.std::string label_or_guest(const Member* member);
// Creates a new Member and gives it to the caller, who then owns it.// Returned by value: the caller receives the object itself, named// "Guest <id>", not a pointer to something someone else owns.Member make_guest(int id);Without reading the bodies, you know: label reads and keeps nothing; rename
changes the caller’s member; label_or_guest accepts a member that may not
exist; and make_guest hands a brand-new Member to the caller, who owns it
from then on. The Member type is a plain struct:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One library member: an ID number and a name. Plain data with no rule// linking the two, so a struct with public members.struct Member { int id = 0; std::string name;};An owner that hands out observers
Section titled “An owner that hands out observers”A directory of members owns them all and lets other code find them:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The owner of every Member: they live inside it, by value. Other code// gets pointers that let it look at (observe) a member, but never own it.class MemberDirectory {public: // Stores a new member and returns a non-owning pointer to it, or // nullptr (storing nothing) if the ID is taken. // `name` is taken by value because the directory keeps it (a sink // parameter); it is moved into the stored Member. Member* add(int id, std::string name);
// Nullable, non-owning observers: nullptr means "no such member". // Two versions with the same name (an overload). C++ picks one by the // directory you call it on: on a const directory, the const version, // which gives read-only access; otherwise the second, which lets the // caller change the member through the pointer. [[nodiscard]] const Member* find(int id) const; [[nodiscard]] Member* find(int id);
// Destroys the member; pointers to it dangle afterwards. // erase(id) removes the entry with that key and returns how many it // removed: 1 if the ID was there, 0 if not. So the result is true // exactly when a member was removed. bool remove(int id) { return members_.erase(id) == 1; }
private: // A std::map keeps (key, value) pairs sorted by key, here ID to Member. // Each key appears at most once, and an element stays at the same // address until it is erased, which is what keeps find's pointers valid. std::map<int, Member> members_; // owns the members};The members are stored by value in a std::map, so the directory owns them and
they are destroyed when they are removed or when the directory is destroyed.
find returns a pointer, because “no such member” is a normal answer, and
nullptr expresses it. It has two versions: the const one gives read-only
access when the directory is const, and the other allows changes.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// try_emplace(key, value) inserts the pair only if the key is not already// in the map. It returns two things, which `auto [it, inserted]` (a// structured binding) unpacks into two names:// - `it`, an iterator to the entry with that key: the new one, or the one// that was already there;// - `inserted`, true if a new entry was added, false if the ID was taken.// The Member{id, std::move(name)} argument is built before the call; if// the ID was taken it is simply thrown away, and the map is unchanged.// A map entry is a pair: it->first is the key (the ID), it->second is the// Member. `&it->second` is the address of the stored Member, the pointer// handed back to the caller.Member* MemberDirectory::add(int id, std::string name) { auto [it, inserted] = members_.try_emplace(id, Member{id, std::move(name)}); return inserted ? &it->second : nullptr;}
// members_.find(id) returns an iterator to the entry with that key, or// members_.end(), a "one past the last" position that means "not found".// `?:` turns that into the pointer answer: nullptr, or the Member's address.// In this const version the map is const, so the result can only be a// pointer to const.const Member* MemberDirectory::find(int id) const { auto it = members_.find(id); return it == members_.end() ? nullptr : &it->second;}
// The same search on a non-const directory, so the pointer allows changes.Member* MemberDirectory::find(int id) { auto it = members_.find(id); return it == members_.end() ? nullptr : &it->second;}How this code works: MemberDirectory::add and find
Take an empty directory and three calls, as in the first test on this page.
add(1, "Ada"). AMember{1, "Ada"}is built, andtry_emplacefinds no key 1 in the map, so it stores the pair (1, Ada). It returns an iterator to the new entry andinserted == true.addreturns&it->second: the address of theMembernow living inside the map. The caller gets a pointer to look through, but the map still owns theMember.add(1, "Someone else"). A temporaryMember{1, "Someone else"}is built, but key 1 is already there, sotry_emplacestores nothing. It returns an iterator to the existing Ada entry andinserted == false, soaddreturnsnullptr. The temporary is destroyed at the end of the statement; Ada is untouched.find(1).members_.find(1)returns an iterator to Ada’s entry, which is notend(), sofindreturns Ada’s address.find(3)would getend()back and returnnullptr.
Both pointers returned for Ada, from step 1 and step 3, are the same address,
and they stay valid however many other members are added or removed, because a
std::map never moves an element once it is stored. Only remove(1), or the
end of the directory, destroys Ada and leaves those pointers dangling.
A pointer returned by find is valid until that member is removed or the
directory is destroyed. That promise depends on the container: std::map never
moves its elements when others are inserted or erased, so the promise holds.
With a std::vector, adding an element may move all the existing ones to a new,
larger block of memory, and every pointer into the vector would dangle. The
choice of container is part of the ownership design, and the header comment
records the promise.
A class that borrows for its whole life
Section titled “A class that borrows for its whole life”LoanDesk uses a directory for as long as the desk exists, but does not own it:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Uses a directory it does not own. Taking a reference in the constructor// says "must not be null"; storing a pointer keeps LoanDesk assignable.class LoanDesk {public: // `&directory` takes the address of the caller's directory and stores // it. The desk now points at that directory; nothing is copied, and // the desk will never delete it. explicit LoanDesk(MemberDirectory& directory) : directory_(&directory) {}
// Returns the greeting for a member, or an explanation if absent. [[nodiscard]] std::string greet(int member_id) const;
private: // The type alone would allow null; the constructor is what guarantees // it is not. The directory must outlive the desk: nothing checks that. MemberDirectory* directory_; // non-owning, never null};Two details are deliberate.
- The constructor takes a reference, which says “you must give me a directory; null is not allowed”.
- The member is a pointer, not a reference. A reference member would make
LoanDeskimpossible to assign (a reference cannot be re-bound), for no benefit. The comment “non-owning, never null” records what the type cannot.
The cost of this design is a lifetime rule the compiler does not check: the directory must outlive the desk. The header comment states it. In the program below, the directory is created first, so it is destroyed last, and the rule holds.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The directory is created first, so it is destroyed last: it outlives// the desk, which is the lifetime rule LoanDesk depends on.MemberDirectory directory; // owns the membersdirectory.add(1, "Ada"); // the returned pointers are not needed heredirectory.add(2, "Grace");
LoanDesk desk(directory); // borrows the directorystd::cout << desk.greet(1) << '\n'; // "hello, Ada"
// Declare and test in one go: the body runs only if find did not// return nullptr. `*grace` follows the pointer to the Member itself,// which rename and label take by reference.if (Member* grace = directory.find(2)) { // observe, then modify rename(*grace, "Grace H."); // changes the Member stored in the directory std::cout << label(*grace) << '\n'; // "#2 Grace H."}
// There is no member 3, so find returns nullptr, and label_or_guest// is written to accept that: it prints "guest".std::cout << label_or_guest(directory.find(3)) << '\n'; // null is allowed
directory.remove(1); // Ada is destroyed here// The desk holds a pointer to the directory, not to Ada, so it is// still safe to use: it looks member 1 up again and finds nobody.std::cout << desk.greet(1) << '\n'; // "no member 1"
Member guest = make_guest(7); // the caller owns the returned valuestd::cout << label(guest) << '\n'; // "#7 Guest 7"hello, Ada#2 Grace H.guestno member 1#7 Guest 7After directory.remove(1), Ada is destroyed. The desk does not hold a pointer
to Ada, only to the directory, so it simply finds no member 1. That is safer than
caching a Member* inside the desk, which would dangle.
Text description of the diagram
Solid arrows mean “owns”; dashed arrows mean “observes without owning”. The scope
of main owns three objects: the MemberDirectory, the LoanDesk, and the
guest Member returned by make_guest. The directory owns the members stored
in it, such as Grace. The desk observes the directory. A pointer returned by
find observes Grace. Every object has exactly one owner, the references and
pointers only observe, and each observer’s target is owned by something that lives at least as long as the observer.
Diagram source (Mermaid)
flowchart LR
main(["main's scope"]) --> Dir[MemberDirectory]
main --> Desk[LoanDesk]
main --> Guest["Member: guest"]
Dir --> Grace["Member: Grace"]
Desk -.->|observes| Dir
P(["pointer from find"]) -.->|observes| GraceDangling: when an observer outlives the object
Section titled “Dangling: when an observer outlives the object”A reference or pointer whose object has been destroyed is a dangling reference. Using it has undefined behaviour: the program may crash, print garbage, or appear to work until a change elsewhere.
The classic case is returning a reference to a local variable:
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
const std::string& make_label(const Member& member) { std::string label = "#" + std::to_string(member.id); return label; // label is destroyed here; the caller gets a dangling reference}GCC and Clang warn about this one, and this site’s builds treat warnings as
errors, so it would not even compile here. The fix is to return by value:
std::string make_label(const Member&).
The dangerous cases are the ones compilers often miss. This accessor is perfectly correct on its own:
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// Fine on its own: the reference is valid as long as `member` is.// It hands back a reference to the name stored inside the caller's// Member, so nothing is copied. The catch: the result is only as good as// the Member it came from. The function cannot know how long that is.const std::string& name_of(const Member& member) { return member.name; }But here it is called on a temporary:
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// load_member returns a temporary Member, destroyed at the end of this// statement. `name` is left referring to a string that no longer exists.// Step by step: (1) load_member(1) makes a temporary Member, with no// variable name; (2) name_of binds its parameter to it and returns a// reference to its `name` member; (3) `name` is bound to that returned// reference; (4) the semicolon ends the statement, and the temporary// Member, with its string, is destroyed. Binding `name` directly to a// temporary would have kept the temporary alive; binding it to a// reference returned by a function does not.const std::string& name = name_of(load_member(1));// The bug shows here: this reads a destroyed string. It may print// "Ada", print garbage, or crash; nothing about it is guaranteed.std::cout << name << '\n'; // undefined behaviourload_member(1) returns a temporary Member, which is destroyed at the end of
the statement (the lifetime lesson’s rule 2). name now refers to a string
inside a destroyed object. Binding a reference directly to a temporary can extend
the temporary’s lifetime, but not here: name is bound to the reference that
name_of returns, not to the temporary itself. GCC 11 and Clang 14 compile this
without a warning under this site’s warning flags; the program is compiled to show
that, but never run. Newer GCC versions (13 and later) may warn about this exact
shape through -Wdangling-reference, but compilers cannot catch every variant,
so do not rely on them.
Fixes, from most to least preferred:
- Keep a copy when you need the value later:
const std::string name = name_of(load_member(1));copies the string before the temporary is destroyed. - Keep the object alive:
const Member member = load_member(1);and then usename_of(member)whilememberis in scope. - Do not return references to parts of parameters unless callers clearly expect it; return by value when in doubt.
Testing the observers
Section titled “Testing the observers”The tests check the ownership promises the header makes: duplicate IDs are rejected, pointers stay valid when other members change, removed members cannot be found, and a null observer is handled.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST, LLD_CHECK, and LLD_CHECK_EQ come from the site's test header,// lld_test.hpp (explained with the first lesson's tests).
// A second add with the same ID returns nullptr, and the first member is// still there, unchanged.LLD_TEST(add_rejects_duplicate_id) { MemberDirectory directory; LLD_CHECK(directory.add(1, "Ada") != nullptr); LLD_CHECK(directory.add(1, "Someone else") == nullptr); LLD_CHECK_EQ(directory.find(1)->name, std::string("Ada"));}
// The promise in the header comment: keep a pointer to Ada, then add 98// more members (IDs 2 to 99) and remove one. The pointer must still be// the address find gives for ID 1, and still reach "Ada". With a// std::vector instead of a std::map, the 98 adds would almost certainly// move Ada to new memory and leave `ada` dangling.LLD_TEST(pointers_stay_valid_when_other_members_change) { MemberDirectory directory; Member* ada = directory.add(1, "Ada"); for (int id = 2; id < 100; ++id) directory.add(id, "Member"); directory.remove(50); LLD_CHECK(ada == directory.find(1)); // std::map does not move elements LLD_CHECK_EQ(ada->name, std::string("Ada"));}
// remove reports true the first time, after which find gives nullptr and// a second remove of the same ID reports false.LLD_TEST(find_returns_null_for_missing_or_removed_member) { MemberDirectory directory; directory.add(1, "Ada"); LLD_CHECK(directory.remove(1)); LLD_CHECK(directory.find(1) == nullptr); LLD_CHECK(!directory.remove(1));}
// The desk borrows the directory rather than copying it, so a member// added to the directory after the desk was built is visible to the desk.LLD_TEST(desk_sees_changes_made_through_the_directory) { MemberDirectory directory; const LoanDesk desk(directory); LLD_CHECK_EQ(desk.greet(1), std::string("no member 1")); directory.add(1, "Ada"); LLD_CHECK_EQ(desk.greet(1), std::string("hello, Ada"));}
// Both cases of a nullable parameter: nullptr, and the address of a real// Member (`&ada`).LLD_TEST(nullable_parameter_handles_null) { LLD_CHECK_EQ(label_or_guest(nullptr), std::string("guest")); const Member ada{1, "Ada"}; LLD_CHECK_EQ(label_or_guest(&ada), std::string("#1 Ada"));}Tests cannot prove the absence of dangling references, because undefined behaviour may look fine in a test. The sanitizer builds (described in the build basics lesson) run these tests with checks that detect many uses of destroyed objects. The best defence is still a design in which observers obviously cannot outlive their targets.
When to use each kind of observer
Section titled “When to use each kind of observer”const T&/T¶meter: the default for “use this object during the call”. Never null.const T*/T*parameter or return value: when “no object” is a normal case, such as the result of a lookup.T*data member, set from aT&constructor parameter: a long-lived observer, such asLoanDesk. Only when the target is guaranteed to outlive the observer.- Neither: if you cannot state who keeps the target alive, do not store a reference or raw pointer. Store a copy, an ID to look up later, or use shared ownership deliberately (the smart pointers lesson).
std::optional<T> (C++17) is an alternative to a pointer when a function
creates a result that may be absent: it holds a value or nothing, and owns the
value. A pointer is right when the result is an existing object owned elsewhere.
Common mistakes
Section titled “Common mistakes”- Owning through a raw pointer.
Member* m = new Member{...};makes the caller responsible fordelete, and every early return or exception can leak it. Use a value or a smart pointer. - Pointer parameters that are never null. A
T*parameter tells readers that null is allowed. If it is not, takeT&. - Storing a pointer to an element of a growing
std::vector. It dangles when the vector grows. - Caching an observer of something that may be removed. Store the ID, and look the object up each time.
- Undocumented lifetime rules. If a class stores a pointer, its header must say what must outlive what.
When a requirement changes
Section titled “When a requirement changes”New requirement: “A loan desk can be moved between branches, each with its own member directory.”
Because LoanDesk stores a pointer, it can be re-pointed: add
void switch_directory(MemberDirectory& directory). Had it stored a reference
member, this change would have meant redesigning the class. The lifetime rule
changes too: now each directory the desk is pointed at must outlive the period
during which the desk uses it, so the comment must say that. If branches can
close while desks still refer to them, the lifetime rule can no longer be
guaranteed by structure, which is the point at which the smart pointers lesson
(std::shared_ptr and std::weak_ptr) becomes relevant.
Exercise: Classify signatures by ownership intent
For each signature, say who owns the object afterwards, whether null is allowed, and whether the function may change the object. Name any signature that is misleading, and suggest a better one.
void print_card(const Member& member);Member* find_by_name(std::string_view name);void enroll(Member* member);(the function dereferencesmemberwithout checking it)Member create_member(std::string name);void archive(std::unique_ptr<Member> member);const std::vector<Loan>& loans_of(const Member& member);(it builds a vector in a local variable and returns it)
Show the explained answer
- Caller keeps ownership; never null; read-only. A correct signature.
- Directory (or whoever stores the members) keeps ownership; may return null; the caller may change the member. Correct for a lookup. Its comment should say how long the pointer stays valid.
- Misleading. A pointer parameter says null is allowed, but the function
would crash (undefined behaviour) on null. Use
void enroll(Member& member);. - The caller owns the new
Member(returned by value). Correct. - Ownership transfers to
archive: the caller must pass the pointer withstd::move, and afterwards no longer owns the member. Correct ifarchivereally keeps or destroys it (the smart pointers lesson). - Wrong: returns a reference to a local, which dangles as soon as the
function returns. Return by value:
std::vector<Loan> loans_of(const Member& member);. (Compilers usually warn about this exact form.)
Summary
Section titled “Summary”- Every object needs exactly one clear owner; most code only observes.
- Values, containers, and smart pointers own. References and raw pointers only observe.
- Use references for “always present” and pointers for “may be absent”.
- A long-lived observer creates a lifetime rule the compiler does not check; write it down, and prefer designs where it obviously holds.
- References and pointers dangle when their object is destroyed first; returning references to locals or temporaries is the most common cause.