Skip to content

Chapter 27 of 31

Smart Pointers

Express unique, shared, and observing ownership with modern RAII types.

36 minutes 10 quick checksBy Subha Prasad
Lesson 27 of 31Course navigation

Lesson content

Read, practise, then check your understanding

Smart pointers release dynamically owned objects automatically. std::unique_ptr<T> represents one owner, is movable but not copyable, and should be the default dynamic ownership type.

#include <memory>
#include <utility>

auto source = std::make_unique<int>(42);
auto destination = std::move(source);
// source is now empty

Pass a unique pointer by value when a function takes ownership. Pass T&, const T&, or T* when it only uses the object. get() observes without transferring; release() relinquishes ownership and should be rare. Custom deleters adapt non-delete resources.

Shared and weak ownership

std::shared_ptr maintains a thread-safe strong reference count and destroys the object after the final owner leaves. std::make_shared commonly combines object and control-block allocation. Shared ownership has semantic and performance cost, so use it only when several independent lifetimes genuinely co-own one object.

Cycles of shared pointers never reach zero. std::weak_ptr observes a shared object without extending its lifetime; lock() safely produces a shared pointer or an empty result. Avoid constructing multiple unrelated shared pointers from the same raw pointer, which creates separate control blocks and double deletion. enable_shared_from_this supports obtaining shared ownership from an already shared-managed object, but only after such ownership exists.

Knowledge check

Answer every question correctly to complete this chapter.

Which smart pointer expresses unique ownership?
Which helper constructs unique ownership safely?
Which smart pointer uses shared ownership counting?
What breaks shared_ptr ownership cycles?
Should shared_ptr be used when ownership is not actually shared?
How is a unique_ptr transferred?
What does unique_ptr::get return?
What does unique_ptr::release do?
When does weak_ptr::lock return an empty shared_ptr?
Why prefer make_shared?

0 of 10 checks passed

Your progress is saved on this device.