Smart Pointers
Prerequisites: RAII & resource management
A smart pointer applies RAII to heap memory itself, so
delete is called automatically — modern C++ code rarely calls
new/delete directly at all.
#include <memory>
std::unique_ptr<int> owned = std::make_unique<int>(42);
std::cout << *owned << std::endl; // 42
// automatically deleted when owned goes out of scope
std::shared_ptr<int> shared1 = std::make_shared<int>(10);
std::shared_ptr<int> shared2 = shared1; // both now own it
std::cout << shared1.use_count() << std::endl; // 2
// deleted automatically once the LAST shared_ptr to it is gone
std::unique_ptr allows exactly one owner (it can be moved — see
Move Semantics — but not copied); std::shared_ptr uses reference
counting to allow multiple owners, at a small runtime cost for
maintaining that count.
Common mistakes
- Reaching for
std::shared_ptrby default — preferstd::unique_ptrunless shared ownership is a genuine requirement; it's cheaper and makes ownership unambiguous. - Creating a reference cycle with two
shared_ptrs pointing at each other — neither's count ever reaches zero, leaking both (fixed withstd::weak_ptrfor the back-reference, in real code).
Practice
Create a std::unique_ptr<std::string> holding "Hello" and print
its contents.
Show solution
std::unique_ptr<std::string> greeting = std::make_unique<std::string>("Hello");
std::cout << *greeting << std::endl;