Lesson 8 of 45 · C++
Lesson 16: Smart Pointers – unique_ptr, shared_ptr, weak_ptr
Duration: 12 min
Lesson 8 of 45 · C++
Duration: 12 min
unique_ptr, shared_ptr, weak_ptr\n\nSmart pointers encapsulate raw pointers and automatically free resources when they go out of scope, embodying the RAII principle.\n\n---\n\n## unique_ptr\ncpp\nstd::unique_ptr<int> up = std::make_unique<int>(42);\nstd::cout << *up << '\\n'; // automatically deleted at end of scope\n\nunique_ptr has exclusive ownership – it cannot be copied, only moved.\n\n## shared_ptr\ncpp\nstd::shared_ptr<std::string> sp1 = std::make_shared<std::string>(\"Hello\");\nstd::shared_ptr<std::string> sp2 = sp1; // reference count becomes 2\nstd::cout << *sp2 << '\\n';\nstd::cout << \"use count = \" << sp1.use_count() << '\\n';\n\nshared_ptr maintains a reference count; the object is destroyed when the count drops to zero.\n\n## weak_ptr\ncpp\nstd::weak_ptr<std::string> wp = sp1; // does not affect count\nif (auto locked = wp.lock()) {\n std::cout << *locked << \" (still alive)\\n\";\n} else {\n std::cout << \"Object expired\\n\";\n}\n\nweak_ptr breaks cycles that could otherwise leak memory.\n\n> Tip: Use unique_ptr by default. Upgrade to shared_ptr only when shared ownership is truly required.\n\n---\n\n<Alert type="warning">Never mix raw pointers with smart pointers for the same resource; it defeats automatic cleanup.