unique_ptr & shared_ptr
Ownership written into the type, so the compiler enforces what a comment used to.
Before you start
Manual new/delete is where most C++ memory bugs live. **Smart pointers** wrap a raw pointer in an RAII object that deletes automatically when it goes out of scope, so you cannot forget.
There are two flavours. unique_ptr says "one owner only" — the object is destroyed when its unique pointer dies. shared_ptr says "multiple owners, last one turns out the lights" — it keeps a count of how many pointers refer to the object and deletes when the count hits zero.
This lesson watches a unique_ptr transfer ownership on move, and a shared_ptr count go up and down as references come and go.
Stack
Heap
freed by a destructor, never by a free() you writeOne owner. No delete anywhere in this program, and no leak either.
Step 1 of 7. make_unique allocates and takes sole ownership. `std::make_unique<Node>(7)` allocates a `Node` on the heap and wraps the pointer in a `unique_ptr`. When `u` is destroyed, so is the `Node`. The `unique_ptr` itself is just a pointer — usually the same size as a raw one. The ownership rule is enforced at compile time, not by extra runtime data.
Step 01 / 07
make_unique allocates and takes sole ownership
std::make_unique<Node>(7) allocates a Node on the heap and wraps the pointer in a unique_ptr. When u is destroyed, so is the Node.
The unique_ptr itself is just a pointer — usually the same size as a raw one. The ownership rule is enforced at compile time, not by extra runtime data.
#include <memory>struct Node { int value; };void take(std::unique_ptr<Node> owned) { // owned destroys the Node when this returns}int main() { auto u = std::make_unique<Node>(7); // auto copy = u; // won't compile: unique_ptr is move-only auto moved = std::move(u); // ownership transferred auto s1 = std::make_shared<Node>(9); auto s2 = s1; // refcount 1 -> 2 s2.reset(); // refcount 2 -> 1 take(std::move(moved)); // destroyed inside take() return 0;}