Smart pointers — automatic memory management.
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; // Reference count +110std::cout << sptr1.use_count(); // 21112// weak_ptr — non-owning reference13std::weak_ptr<int> wptr = sptr1;14if (auto locked = wptr.lock()) {15 std::cout << *locked;16}
Types:
unique_ptr — exclusive, lightweight.shared_ptr — shared, reference counting.weak_ptr — non-owning, breaks cycles.