Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Lesson 16: Smart Pointers – unique_ptr, | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

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.

4 points
  • Exclusive ownership with unique_ptr
  • Reference counting with shared_ptr
  • Breaking cycles using weak_ptr
  • Custom deleters

Smart Pointers – unique_ptr, shared_ptr, weak_ptr

Smart pointers encapsulate raw pointers and automatically free resources when they go out of scope, embodying the RAII principle.


unique_ptr

std::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_ptr

std::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_ptr

std::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_ptr by default. Upgrade to shared_ptr only when shared ownership is truly required.


<Alert type="warning">Never mix raw pointers with smart pointers for the same resource; it defeats automatic cleanup.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 15: Dynamic Memory Allocation (new, delete)Continue to lesson 17Lesson 17: Structs and EnumsBack to C++ Course curriculum