Memory Management and What’s Next
Stack vs heap
Ordinary variables live on the stack and are cleaned up automatically the moment they go out of scope — no extra code required. Memory you allocate manually with new lives on the heap instead, and stays reserved until you explicitly free it yourself with delete.
int* score = new int(90); // allocated on the heapnstd::cout << *score;ndelete score; // must be freed manually, or this memory leaks forever
Forgetting to call delete causes a memory leak — that memory stays reserved for the lifetime of the program, even though nothing can reach it anymore. In a long-running program like a game engine or a server, leaks like this accumulate and eventually exhaust available memory entirely.
Smart pointers — the modern approach
#include <memory>nnstd::unique_ptr<int> score = std::make_unique<int>(90);n// no delete needed -- it is freed automatically when score goes out of scope
Modern C++ code reaches for std::unique_ptr and std::shared_ptr instead of raw new/delete — they wrap a raw pointer and automatically call delete for you at the right moment, preventing the whole class of leaks and dangling-pointer bugs that plagued older C++ code.
unique_ptr vs shared_ptr
std::shared_ptr<int> a = std::make_shared<int>(90);nstd::shared_ptr<int> b = a; // both now share ownership -- allowedn// the memory is only freed once the LAST shared_ptr to it is gone
unique_ptr guarantees exactly one owner at a time and cannot be copied, only moved. shared_ptr allows multiple owners simultaneously by keeping an internal reference count, freeing the memory only once that count reaches zero. Default to unique_ptr unless you genuinely need shared ownership — it has less overhead and makes ownership easier to reason about.
Onward to the advanced lessons
You now know C++ syntax, functions, pointers, containers, classes, and basic memory management. The next three lessons take you to a professional level: templates, the STL in depth, and modern move semantics.