RAII and smart pointers
โ Report an issue with this lessonRAII (Resource Acquisition Is Initialization) is C++'s core memory
philosophy: tie a resource's lifetime to an object's scope, so it's
released automatically when that object goes out of scope -- no manual
cleanup, no leaks from a forgotten delete.
std::unique_ptr<Course> course = std::make_unique<Course>("C++ Mastery");
// automatically deleted when `course` goes out of scope
std::shared_ptr<Course> shared = std::make_shared<Course>("Rust Mastery");
auto shared2 = shared; // reference count now 2, freed when both go out of scope
Modern C++ code almost never calls new/delete
directly -- unique_ptr and shared_ptr handle it
correctly, including in the presence of exceptions.
Try it yourself
Exercise: Using std::unique_ptr, create a Course object with title "C++ Mastery" inside an inner scope block, print its title, then let the block end so its destructor runs automatically before "Done" is printed.
Expected output:
Creating: C++ Mastery C++ Mastery Destroying: C++ Mastery Done
Run your code and get it working before marking this lesson complete.
// that was the last free lesson
9 more lessons โ including Project: build a thread-safe task queue โ and a final exam plus a certificate are waiting.
Unlock the full course โ $99.99