Smart pointers — automatic memory management via RAII.
1#include <memory>23// unique_ptr — exclusive ownership4auto ptr1 = std::make_unique<int>(10);5auto ptr2 = std::move(ptr1); // Transfer67// shared_ptr — shared ownership8auto sptr1 = std::make_shared<int>(20);9auto sptr2 = sptr1; // ref count +11011// weak_ptr — non-owning reference12std::weak_ptr<int> wptr = sptr1;13if (auto locked = wptr.lock()) {14 std::cout << *locked;15}
Types:
unique_ptr — exclusive, lightweight.shared_ptr — shared, reference counting.weak_ptr — non-owning, breaks cycles.