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.
0 of 10 checks passed
Your progress is saved on this device.