Modern C++ • C++20 baseline
Smart Pointers and Ownership Choices
Choose unique, shared, or non-owning access based on the ownership model.
std::unique_ptr expresses exclusive ownership and is movable but not copyable. std::shared_ptr uses reference counting when ownership is genuinely shared, while std::weak_ptr observes a shared object without extending its lifetime. Reference cycles can keep shared objects alive indefinitely.
Key points
- Prefer unique ownership by default.
- Do not use shared_ptr just to avoid deciding who owns an object.
Example
#include <memory>
struct Node {
int value;
std::unique_ptr<Node> next;
};
int main() {
auto head = std::make_unique<Node>(Node{1, nullptr});
head->next = std::make_unique<Node>(Node{2, nullptr});
}
What to expect
The linked nodes are destroyed automatically when head leaves scope.
Practice exercise
Sketch a parent-child graph and mark which direction owns. Identify where a weak_ptr might be needed.
Key idea: Ownership should be apparent from the type and object graph.