9.6 — Dynamic memory and smart pointers
Read one box at a time. No rush.
Asking for memory while running#
Sometimes you need to create something while the program runs, and keep it alive longer than one function. Old C++ used new and delete:
C++ — wrong ✗
int* p { new int { 5 } }; // ask for memory// ... use *p ...delete p; // give it back — easy to forget!If you forget delete, the memory is never given back. That's a memory leak.
Smart pointers do it for you#
A smart pointer cleans up automatically when it's no longer needed.
C++
#include <memory> auto p { std::make_unique<int>(5) };std::cout << *p; // 5// no delete needed! freed automatically at the end of the blockThe two main kinds#
std::unique_ptr= one owner. When it goes away, the memory is freed. Use this by default.std::shared_ptr= many owners. Freed when the last owner goes away. Make withstd::make_shared.
C++
auto a { std::make_shared<std::string>("hi") };auto b { a }; // a and b share itGood habit
In modern C++, you almost never need new and delete. Use std::vector for lists, and std::make_unique when you need a single object created dynamically.
Tip: press ← / → to move between lessons, / to search.