Lesson 16 of 45
C++Lesson 16: Smart Pointers – unique_ptr, shared_ptr, weak_ptr
12 min
Course progress36%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 16 of 45
C++12 min
Keep these ideas in mind as you work through the lesson.
unique_ptr, shared_ptr, weak_ptrSmart pointers encapsulate raw pointers and automatically free resources when they go out of scope, embodying the RAII principle.
unique_ptrstd::unique_ptr<int> up = std::make_unique<int>(42);
std::cout << *up << '\
'; // automatically deleted at end of scope
unique_ptr has exclusive ownership – it cannot be copied, only moved.
shared_ptrstd::shared_ptr<std::string> sp1 = std::make_shared<std::string>(\"Hello\");
std::shared_ptr<std::string> sp2 = sp1; // reference count becomes 2
std::cout << *sp2 << '\
';
std::cout << \"use count = \" << sp1.use_count() << '\
';
shared_ptr maintains a reference count; the object is destroyed when the count drops to zero.
weak_ptrstd::weak_ptr<std::string> wp = sp1; // does not affect count
if (auto locked = wp.lock()) {
std::cout << *locked << \" (still alive)\
\";
} else {
std::cout << \"Object expired\
\";
}
weak_ptr breaks cycles that could otherwise leak memory.
Tip: Use
unique_ptrby default. Upgrade toshared_ptronly when shared ownership is truly required.
<Alert type="warning">Never mix raw pointers with smart pointers for the same resource; it defeats automatic cleanup.