Smart pointers: unique_ptr, shared_ptr, weak_ptr
What you will learn on this page
Section titled “What you will learn on this page”- Why values come first, and when an object needs to live behind a pointer.
- How
std::unique_ptrexpresses exclusive ownership and its transfer. - When
std::shared_ptris justified, and what it costs. - How
std::weak_ptrobserves without owning, and how it breaks reference cycles. - How to write function signatures that take or return smart pointers.
Values first
Section titled “Values first”The previous lessons established the default: own objects by value, as local variables, members, or container elements. Values need no pointers, no allocation, and no thought about who deletes what.
Sometimes an object cannot simply be a value:
- Polymorphism. A member that can hold “any kind of fee policy” cannot be a
FeePolicyvalue, because of slicing (see the value semantics lesson). It must be held through a pointer (or reference) to the base class. - Lifetime not tied to one scope. An object is created in one place and must outlive it, or is handed from one owner to another.
- Identity that must stay put. Other code holds observers of the object, and the object must not move in memory.
- Genuinely shared lifetime. Several parts of the program use an object, and it should live as long as the longest of them, with no single obvious owner.
For these cases, the object is created on the heap (memory not tied to any
scope) and owned through a smart pointer. A smart pointer is an RAII class
that owns a heap object and destroys it in its destructor. Never own with a raw
pointer and new/delete; every early return and exception becomes a potential
leak, exactly the problem RAII solves.
std::unique_ptr: exactly one owner
Section titled “std::unique_ptr: exactly one owner”A std::unique_ptr<T> owns one
object, and only one unique_ptr can own it at a time. It cannot be copied, only
moved: moving transfers ownership, and the source becomes null. When the
unique_ptr is destroyed or given a new object, it deletes the object it owned.
With the default deleter it is the same size as a raw pointer and has
essentially no run-time overhead.
Here a loan registry needs a fee policy, and there are several kinds:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// An interface: "something that can work out a late fee". The registry// holds one through a pointer to this base class and does not know which// kind it has. `virtual` means a call goes to the version in the actual// object's class; `= 0` means this class has no version of its own, so a// FeePolicy by itself cannot be created, only a class derived from it.class FeePolicy {public: // Virtual, so that deleting a FlatFee through a FeePolicy pointer (as // std::unique_ptr<FeePolicy> does) runs FlatFee's destructor too. virtual ~FeePolicy() = default; [[nodiscard]] virtual int fee_for(int days_late) const = 0;};
// The same fee for every day late: 3 days at 10 per day is 30.// `: public FeePolicy` makes FlatFee one kind of FeePolicy, and `override`// asks the compiler to check that fee_for really replaces the base version.class FlatFee : public FeePolicy {public: explicit FlatFee(int per_day) : per_day_(per_day) {} [[nodiscard]] int fee_for(int days_late) const override { return days_late * per_day_; }
private: int per_day_;};
// No fee for the first `grace_days` days late, then `per_day` for each day// after that. With grace 2 and 10 per day: 2 days late costs 0, 3 days// late costs (3 - 2) * 10 = 10.class GracePeriodFee : public FeePolicy {public: GracePeriodFee(int grace_days, int per_day) : grace_days_(grace_days), per_day_(per_day) {} // `a ? b : c` is "if a, then b, otherwise c". [[nodiscard]] int fee_for(int days_late) const override { return days_late <= grace_days_ ? 0 : (days_late - grace_days_) * per_day_; }
private: int grace_days_; int per_day_;};FeePolicy is an interface (the inheritance lesson covers virtual and = 0
in detail). Its destructor is virtual, which is required when objects are
destroyed through a base-class pointer, as unique_ptr<FeePolicy> does.
The registry owns exactly one policy at a time, and nothing else needs to own it,
so std::unique_ptr<FeePolicy> is the right owner:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Opens and closes loans, and works out late fees with whichever fee// policy it currently owns. The member types say who owns what: one// policy owned alone (unique_ptr), the current rules shared with the loans// opened under them (shared_ptr), and the loans themselves held by value.class LoanRegistry {public: // Takes ownership of the policy (a sink: pass with std::move). // Throws std::invalid_argument if the policy is null. LoanRegistry(std::unique_ptr<FeePolicy> policy, LoanRules rules);
// Replaces the policy; the old one is destroyed here. void set_fee_policy(std::unique_ptr<FeePolicy> policy); // New loans use the new rules; open loans keep the rules they had. void update_rules(LoanRules rules);
int open_loan(std::string title); // returns the loan's ID // Removes the loan; returns false if there was no loan with that ID. bool close_loan(int id);
// The loan with this ID, or nullptr if there is none. The pointer only // lets the caller look: the registry still owns the loan. [[nodiscard]] const Loan* find(int id) const; // `->` calls through the pointer; whichever policy object policy_ // owns (FlatFee or GracePeriodFee) does the calculation. [[nodiscard]] int fee_for(int days_late) const { return policy_->fee_for(days_late); } // Shares the current rules with the caller. // Returning a copy of the shared_ptr makes the caller one more owner. [[nodiscard]] std::shared_ptr<const LoanRules> current_rules() const { return rules_; }
private: std::unique_ptr<FeePolicy> policy_; // exclusive owner, never null std::shared_ptr<const LoanRules> rules_; // shared with open loans std::map<int, Loan> loans_; // values, owned here; ID to loan int next_id_ = 1;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A unique_ptr cannot be copied, so std::move(policy) transfers ownership// from the parameter to the member policy_ (the parameter is left null).// std::make_shared<const LoanRules>(rules) creates one new LoanRules, a// copy of `rules`, on the heap, owned by a shared_ptr whose count is 1.// The null check is on policy_, which now holds what the caller passed. If// it throws, the registry is never created and its members are cleaned up.LoanRegistry::LoanRegistry(std::unique_ptr<FeePolicy> policy, LoanRules rules) : policy_(std::move(policy)), rules_(std::make_shared<const LoanRules>(rules)) { if (policy_ == nullptr) throw std::invalid_argument("a registry needs a fee policy");}
// Checks first, so a null policy is refused and the old one is kept.// Assigning a unique_ptr deletes the object it owned before.void LoanRegistry::set_fee_policy(std::unique_ptr<FeePolicy> policy) { if (policy == nullptr) throw std::invalid_argument("a registry needs a fee policy"); policy_ = std::move(policy); // the previous policy is destroyed}
// rules_ is pointed at a brand-new LoanRules. The registry gives up its// share of the old rules; they are destroyed only if no open loan still// shares them. The old object is never changed.void LoanRegistry::update_rules(LoanRules rules) { rules_ = std::make_shared<const LoanRules>(rules);}
// next_id_++ gives `id` the current value and then adds 1, so IDs run 1,// 2, 3, ... Passing rules_ (not std::move(rules_)) copies the shared_ptr:// the count goes up by one, and the registry keeps its own share.// emplace adds the (id, loan) pair to the map; the temporary Loan is moved// into the map's own storage.int LoanRegistry::open_loan(std::string title) { const int id = next_id_++; loans_.emplace(id, Loan(std::move(title), rules_)); // the loan shares rules_ return id;}Read the ownership from the signatures:
LoanRegistry(std::unique_ptr<FeePolicy> policy, ...)takes the pointer by value. Because aunique_ptrcannot be copied, the caller must hand it over, either as a temporary (std::make_unique<FlatFee>(10)) or withstd::move(ptr). The signature says “I take ownership”.set_fee_policy(std::unique_ptr<FeePolicy> policy)takes ownership of the new policy. Assigning it topolicy_deletes the old one.fee_for(int)uses the policy without exposing ownership. If another function only needed to use a policy, it would takeconst FeePolicy&, not a smart pointer.
std::make_unique<T>(args...) creates the object and its owner in one step; use it
instead of new. The constructor rejects a null policy, so the invariant “the
policy is never null” holds and fee_for does not need to check.
std::shared_ptr: shared ownership, when it is real
Section titled “std::shared_ptr: shared ownership, when it is real”A std::shared_ptr<T> shares
ownership: any number of shared_ptrs can own the same object, which is destroyed
when the last of them is destroyed or reset. It works by keeping a reference
count, the number of owners, in a separate control block. Copying a
shared_ptr increments the count, and destroying one decrements it.
In the registry, loan rules (how many days, how many renewals) change from time to time, but each open loan must keep the rules it was opened under:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Plain data: how long a loan lasts and how often it can be renewed. A// struct with public members, because any pair of values is valid.struct LoanRules { int max_days = 21; int max_renewals = 2;};
// A loan remembers the rules in force when it was opened.// It holds a std::shared_ptr to them, so the loan is one of the rules'// owners: the rules stay alive at least as long as this loan does, even// after the registry has moved on to newer rules. `const LoanRules` means// no owner can change the shared rules.class Loan {public: // Both parameters are taken by value and then moved into the members // (std::move hands over the contents instead of copying them again). // Moving a shared_ptr transfers its share without touching the count. Loan(std::string title, std::shared_ptr<const LoanRules> rules) : title_(std::move(title)), rules_(std::move(rules)) {}
[[nodiscard]] const std::string& title() const noexcept { return title_; } // *rules_ follows the pointer to the shared object and returns a // read-only reference to it. Safe because rules_ is never null. [[nodiscard]] const LoanRules& rules() const noexcept { return *rules_; }
private: std::string title_; std::shared_ptr<const LoanRules> rules_; // shared, never null};This is genuine shared ownership. The registry holds the current rules; every
loan opened under them holds them too. When the rules change, the registry gets a
new LoanRules object, and the old one must live exactly as long as the last
loan that uses it. No single object is the natural owner, so a reference count is
the right tool. Notice that it is a shared_ptr<const LoanRules>: the shared
object is immutable, so sharing it cannot cause one owner’s changes to surprise
another.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// std::make_unique<FlatFee>(10) creates a FlatFee charging 10 per day on// the heap and returns the unique_ptr that owns it. It is a temporary, so// it can be handed straight to the registry, which takes ownership.// LoanRules{21, 2} fills max_days = 21 and max_renewals = 2, in order.LoanRegistry registry(std::make_unique<FlatFee>(10), LoanRules{21, 2});std::cout << "fee for 3 days late: " << registry.fee_for(3) << '\n'; // 3 * 10
// The registry deletes the FlatFee and owns the new policy instead.registry.set_fee_policy(std::make_unique<GracePeriodFee>(2, 10));std::cout << "with a grace period: " << registry.fee_for(3) << '\n'; // (3 - 2) * 10
// Loan 1 shares the 21-day rules with the registry: two owners.const int first = registry.open_loan("Middlemarch");// A weak_ptr watches the 21-day rules without owning them: it does not// keep them alive, it can only report whether they still exist. (The// shared_ptr returned by current_rules is a temporary, gone at the `;`.)std::weak_ptr<const LoanRules> old_rules = registry.current_rules();
// The registry switches to new 14-day rules. Loan 1 is now the only// owner of the 21-day rules, so they stay alive.registry.update_rules(LoanRules{14, 1});const int second = registry.open_loan("Persuasion"); // shares the 14-day rules
// find returns a pointer to the loan, and `->` reaches through it.std::cout << "first loan: " << registry.find(first)->rules().max_days << " days\n";std::cout << "second loan: " << registry.find(second)->rules().max_days << " days\n";// expired() is true once the watched object is gone. main set// std::boolalpha just before this snippet, so a bool prints as true or// false instead of 1 or 0.std::cout << "old rules still alive: " << !old_rules.expired() << '\n';
// Erasing loan 1 destroys it and its shared_ptr; the count of the// 21-day rules drops to 0, so they are destroyed too.registry.close_loan(first); // the last user of the old rulesstd::cout << "old rules still alive: " << !old_rules.expired() << '\n';How this code works: who owns the 21-day rules
Follow one object through main: the first LoanRules, with max_days 21.
Its owner count is the number of shared_ptrs that point at it, which is
what use_count() would report.
| Step | Owners of the 21-day rules | Count |
|---|---|---|
| the registry is constructed | the registry’s rules_ |
1 |
open_loan("Middlemarch") |
rules_, loan 1 |
2 |
old_rules is made from current_rules() |
rules_, loan 1 (a weak_ptr is not an owner) |
2 |
update_rules(LoanRules{14, 1}) |
loan 1 | 1 |
close_loan(first) |
nobody: the rules are destroyed | 0 |
A few details behind the table:
- Opening a loan copies the
shared_ptr.open_loanpassesrules_(notstd::move(rules_)) to theLoanconstructor, so the loan gets its own share and the registry keeps its share. current_rules()returns a copy, a temporaryshared_ptr. For a moment there are three owners; theweak_ptris made from the temporary, and the temporary is destroyed at the end of the statement, leaving two.update_rulesdoes not touch the old object. It pointsrules_at a newLoanRules, which drops the registry’s share of the old one. Loan 1 still owns it, so it lives on, and loan 1 still reports 21 days.- Closing loan 1 erases it from the map. Destroying the loan destroys its
shared_ptr, the count reaches 0, and the 21-day rules are deleted. Theweak_ptrnotices:expired()becomestrue.
The fee lines follow the same “replace the owner” idea with a unique_ptr:
FlatFee(10) charges 3 * 10 = 30 for 3 days late; after set_fee_policy
deletes it, GracePeriodFee(2, 10) charges (3 - 2) * 10 = 10.
fee for 3 days late: 30with a grace period: 10first loan: 21 dayssecond loan: 14 daysold rules still alive: trueold rules still alive: falseThe first loan still reports 21 days after the rules change, because it shares the old rules. When it is closed, the old rules have no owner left, and they are destroyed.
std::weak_ptr: observing a shared object
Section titled “std::weak_ptr: observing a shared object”A std::weak_ptr<T> refers to an object
owned by shared_ptrs, without being an owner itself. It does not keep the object
alive. To use the object, you call lock(), which returns a shared_ptr that
owns it for as long as you hold it, or a null shared_ptr if the object has
already been destroyed. expired() says whether it is gone.
That is what main above uses to watch the old rules: old_rules is a
weak_ptr, so it can report whether the rules are still alive without keeping
them alive itself.
Reference cycles
Section titled “Reference cycles”weak_ptr’s most important job is breaking cycles. In this flawed design, a
reading group owns its readers, and each reader owns its group:
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// FLAWED. A reader and a reading group that point at each other, both// with shared_ptr, so each one counts as an owner of the other.// `struct ReadingGroup;` only announces the name, so Reader can mention// it before the full definition below.struct ReadingGroup;
struct Reader { std::string name; // The mistake: a reader does not need to keep its group alive, only to // find it. Owning it here is what closes the circle. std::shared_ptr<ReadingGroup> group; // owns the group...};
struct ReadingGroup { std::string book; std::vector<std::shared_ptr<Reader>> readers; // ...which owns the reader};Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// FLAWED. Each make_shared creates an object on the heap with a count of// 1 (the local variable). ReadingGroup{"Middlemarch", {}} sets book and// an empty readers list. Reader{"Ada", group} copies `group`, so the// group's count becomes 2: the local `group` and Ada's member.auto group = std::make_shared<ReadingGroup>(ReadingGroup{"Middlemarch", {}});auto ada = std::make_shared<Reader>(Reader{"Ada", group});// push_back copies `ada` into the vector: Ada's count becomes 2 too.group->readers.push_back(ada);// Both counts are now 2. When the locals go, each drops only to 1: the// group's last owner is inside Ada, and Ada's last owner is inside the group.// At the end of main, `group` and `ada` are destroyed, but each object is// still owned by the other: use_count never reaches zero, and neither// destructor runs.When main’s two local shared_ptrs are destroyed, each count drops from 2 to
1, because the group still owns Ada and Ada still owns the group. Neither count
ever reaches 0, so neither object is destroyed: a memory leak that no error
message reports. (A leak checker such as AddressSanitizer would find it, which
is one reason this program is compiled but not run as a test.)
The fix is to decide which direction is ownership and which is only observation. The group owns its readers; a reader merely needs to know its group, if it still exists:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Announces the name ReadingGroup, so Reader can refer to it before the// class is fully defined further down.class ReadingGroup;
// A member of a reading group. It needs to find its group, but must not// keep the group alive, so it holds a std::weak_ptr: a pointer that knows// whether the object still exists but is not counted as an owner.class Reader {public: // The shared_ptr is only read, so it comes in by const reference. // Initialising group_ from it makes a weak_ptr to the same group; the // group's owner count does not change. Reader(std::string name, const std::shared_ptr<ReadingGroup>& group) : name_(std::move(name)), group_(group) {}
[[nodiscard]] const std::string& name() const noexcept { return name_; } // The group's book, or "(group closed)" if the group no longer exists. [[nodiscard]] std::string current_book() const;
private: std::string name_; std::weak_ptr<ReadingGroup> group_; // observes; does not own};
// A group reading one book. It owns its readers through shared_ptr// (shared because a reader may also be held elsewhere). Ownership now// runs one way only, group to reader, so there is no cycle.class ReadingGroup {public: explicit ReadingGroup(std::string book) : book_(std::move(book)) {}
[[nodiscard]] const std::string& book() const noexcept { return book_; } // Takes a shared_ptr by value (one more owner) and moves it into the // vector, so no extra count update is needed. void add(std::shared_ptr<Reader> reader) { readers_.push_back(std::move(reader)); } [[nodiscard]] std::size_t size() const noexcept { return readers_.size(); }
private: std::string book_; std::vector<std::shared_ptr<Reader>> readers_; // owns};
// Defined here, after ReadingGroup is complete, because it calls book().// `inline` lets this definition, written in a header, appear in every file// that includes the header without a "defined twice" link error.inline std::string Reader::current_book() const { // lock() gives a temporary owner, or null if the group is gone. // `if (declaration)` creates `group` and tests it: a shared_ptr counts // as true when it is not null. While `group` exists the group cannot be // destroyed, and the book title is copied into the returned string // before `group` goes away at the end of the if. if (const std::shared_ptr<ReadingGroup> group = group_.lock()) return group->book(); return "(group closed)";}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_CHECK(condition) fails the test if the condition is false, and// LLD_CHECK_EQ(actual, expected) fails it if the two values differ.//// While the group exists, the reader can reach it, and the reader's// weak_ptr is not counted: the group's only owner is the local `group`.LLD_TEST(reader_sees_the_group_while_it_exists) { auto group = std::make_shared<ReadingGroup>("Middlemarch"); auto ada = std::make_shared<Reader>("Ada", group); group->add(ada); LLD_CHECK_EQ(ada->current_book(), std::string("Middlemarch")); // use_count() is the number of shared_ptr owners. It returns a long, // hence 1L, so both sides of the comparison have the same type. LLD_CHECK_EQ(group.use_count(), 1L); // the reader does not add an owner}
// Two weak_ptr "watchers" outlive the inner block. When the block ends,// `ada` is destroyed (Ada's count 2 to 1), then `group` (count 1 to 0), so// the group is destroyed, its vector with it, and Ada's count reaches 0.// Both watchers then report expired: nothing leaked.LLD_TEST(group_and_readers_are_destroyed_without_a_cycle) { std::weak_ptr<ReadingGroup> group_watch; std::weak_ptr<Reader> reader_watch; { auto group = std::make_shared<ReadingGroup>("Middlemarch"); auto ada = std::make_shared<Reader>("Ada", group); group->add(ada); group_watch = group; // observe without owning reader_watch = ada; } LLD_CHECK(group_watch.expired()); LLD_CHECK(reader_watch.expired());}
// `ada` is declared outside the block, so the reader outlives the group.// The group is destroyed at the closing brace; current_book must notice// that through lock() instead of reaching a destroyed object.LLD_TEST(reader_held_elsewhere_outlives_the_group_safely) { std::shared_ptr<Reader> ada; { auto group = std::make_shared<ReadingGroup>("Middlemarch"); ada = std::make_shared<Reader>("Ada", group); group->add(ada); } LLD_CHECK_EQ(ada->current_book(), std::string("(group closed)"));}How this code works: why the fixed reading group is destroyed
Take the second test. Inside the block there are two objects, the group and Ada, and their owners are:
- the group: the local
grouponly (Ada’sweak_ptrdoes not count), so 1; - Ada: the local
adaand the group’sreaders_vector, so 2.
At the closing brace, local variables are destroyed in the reverse order of their creation:
adais destroyed first. Ada’s count drops from 2 to 1; the vector still owns Ada.groupis destroyed next. The group’s count drops from 1 to 0, so the group is destroyed, and with it itsreaders_vector.- Destroying the vector destroys its
shared_ptrto Ada. Ada’s count drops from 1 to 0, so Ada is destroyed too.
Compare the flawed version: there, Ada’s member was a shared_ptr, so the
group started with a count of 2 and step 2 only took it down to 1. The chain
never started. With the weak_ptr, ownership runs one way, from group to
reader, and destruction can follow it.
The tests check that the reader does not add to the group’s reference count, that
both objects are destroyed when the outside owners let go (both weak_ptr
watchers report expired), and that a reader held elsewhere copes when its group
is gone.
Text description of the diagram
Solid arrows own; dashed arrows only observe. The LoanRegistry owns its
FeePolicy exclusively through a unique_ptr, and owns each Loan by value.
The registry and each Loan share
ownership of the LoanRules through shared_ptrs, and a weak_ptr in main
observes the rules without owning them. In the fixed reading-group design, the
ReadingGroup owns each Reader through a shared_ptr, and each Reader refers
back to its group only through a weak_ptr, so there is no ownership cycle.
Diagram source (Mermaid)
flowchart LR
Reg[LoanRegistry] -->|unique_ptr| Policy[FeePolicy]
Reg -->|shared_ptr| Rules[LoanRules]
Reg -->|by value| Loan1
Loan1[Loan] -->|shared_ptr| Rules
W(["weak_ptr in main"]) -.->|observes| Rules
Group[ReadingGroup] -->|shared_ptr| Reader
Reader -.->|weak_ptr| GroupBefore reaching for weak_ptr, ask whether the shared ownership is needed at all.
Often the simplest fix for a cycle is a clear single owner (the group holds
readers by value or unique_ptr) and a plain pointer or an ID for the back
reference. A plain pointer is safe only if the group is guaranteed to outlive its
readers, and an ID only if it is looked up and checked each time. If neither
holds, as in the last test above, where a reader outlives its group, use
weak_ptr.
Smart pointers in function signatures
Section titled “Smart pointers in function signatures”The type you write for a parameter says what the function does with ownership.
IllustrativeA fragment for explanation; not compiled on its own.
void use(const FeePolicy& policy); // uses it; ownership irrelevantvoid use_if_any(const FeePolicy* policy); // may be null; ownership irrelevantvoid adopt(std::unique_ptr<FeePolicy> policy); // takes ownershipvoid keep(std::shared_ptr<const LoanRules> rules); // becomes one more ownerstd::unique_ptr<FeePolicy> make_policy(int kind); // gives ownership to the caller- Only using the object? Take
const T&orT&(orT*if it may be absent), even if the caller holds it in a smart pointer. Pass*ptrorptr.get(). This keeps the function usable with objects owned in any way. - Taking ownership? Take
std::unique_ptr<T>by value. - Becoming one more shared owner? Take
std::shared_ptr<T>by value and move it into place. - Creating an object for the caller? Return
std::unique_ptr<T>by value. The caller can convert it to ashared_ptrlater if needed; the reverse is impossible.
Avoid const std::unique_ptr<T>& parameters: they tie the function to one
ownership style and say nothing a const T& would not. Take a non-const
std::unique_ptr<T>& or std::shared_ptr<T>& only when the function reseats or
resets the caller’s pointer. const std::shared_ptr<T>& is reasonable when the
function only sometimes keeps a copy, because it saves a reference-count update
when it does not; if it only uses the object, take T& or const T&.
When to use each
Section titled “When to use each”| Situation | Choice |
|---|---|
| One owner, object can be a member or local | A value |
| One owner, but polymorphic, must outlive its scope, or must not move | std::unique_ptr<T> |
| Lifetime truly shared, no natural owner | std::shared_ptr<T> (prefer <const T>) |
| Observe a shared object that may disappear | std::weak_ptr<T> |
| Use an object during a call | T&, const T&, or T* |
Common mistakes
Section titled “Common mistakes”shared_ptrby default. It hides who owns what and costs more. Start with values andunique_ptr.- Creating two owners from one raw pointer.
std::shared_ptr<T> a(raw); std::shared_ptr<T> b(raw);gives two separate reference counts, and the object is deleted twice. Create shared objects withstd::make_sharedand copy theshared_ptr. - Calling
newanddeletedirectly. Usestd::make_uniqueandstd::make_shared. - Smart pointer parameters for functions that only use the object. Take a reference instead.
shared_ptrcycles. Decide which direction owns, and make the other direction aweak_ptr, or a raw pointer or an ID if the owner is guaranteed to outlive it.- A missing virtual destructor. Deleting a derived object through a
unique_ptr<Base>whoseBasedestructor is notvirtualhas undefined behaviour.
When a requirement changes
Section titled “When a requirement changes”New requirement: “Members can choose their own fee policy, for example a student discount.”
Each member now needs a policy. If each member’s policy is its own, each
Member gets a std::unique_ptr<FeePolicy> member, and the registry looks up the
member’s policy when computing a fee. If many members share one of a few standard
policies, a std::shared_ptr<const FeePolicy> per member is reasonable: the
policies are immutable and shared, like LoanRules. A third option, often the
simplest, is that the registry owns the few policies (by unique_ptr, in a map)
and each member stores just a policy name or ID. The choice depends on whether
policies can be created per member and how long they must live, which is a
question to ask, not guess.
Exercise: Choose ownership for five scenarios
For each scenario, choose how the object should be owned and referred to, and give the reason.
- A
Libraryhas exactly oneCatalog, created with it and destroyed with it. - A
ReportBuilderis given one of severalReportFormatimplementations (CSV, HTML) when it is constructed, and uses it until it is destroyed. - Image thumbnails are expensive to load. Several open windows may show the same thumbnail; it should stay loaded while any window shows it, and be freed when none does.
- A thumbnail cache maps file names to thumbnails, but must not keep a thumbnail loaded just because it is in the cache.
- A function
print_policyprints a description of aFeePolicy.
Show the explained answer
- A value member:
Catalog catalog_;One owner, same lifetime, no polymorphism. No pointer of any kind is needed. std::unique_ptr<ReportFormat>member, taken by value in the constructor. Exactly one owner, but polymorphic, so it cannot be a value.std::shared_ptr<const Thumbnail>held by each window. Lifetime is truly shared: the thumbnail must live as long as the longest-lived window showing it, and no single window is the natural owner.constbecause the windows only display it.std::weak_ptr<const Thumbnail>in the cache. The cache observes without owning; on lookup it callslock()and, if the thumbnail has expired, loads it again and stores a newweak_ptr.void print_policy(const FeePolicy& policy);It only uses the policy, so ownership is irrelevant. A caller holding aunique_ptr<FeePolicy>passes*ptr.
Scenarios 3 and 4 together form the classic justified use of shared_ptr plus
weak_ptr. Scenarios 1, 2, and 5 are far more common, and none needs shared
ownership.
Summary
Section titled “Summary”- Own by value first. Use a smart pointer when the object is polymorphic, must outlive its scope, must not move, or is truly shared.
std::unique_ptris exclusive ownership with essentially no overhead; it moves, never copies. Create it withstd::make_unique.std::shared_ptris shared ownership by reference count; justify it, prefershared_ptr<const T>, and create it withstd::make_shared.std::weak_ptrobserves a shared object without keeping it alive, and breaks ownership cycles.- Functions that only use an object take a reference or pointer; take or return a smart pointer by value only to transfer or share ownership.