The engine will hold policy rules chosen at run time: a total limit today, perhaps a per-item limit tomorrow. Objects whose concrete type is decided at run time usually live on the heap, and every heap object raises the same question: who destroys it, and when? With raw new and delete, the answer is "whoever remembers to", on every path out of every function, including the early returns added months later. That is how leaks and double frees happen.
C++ answers the question with RAII, resource acquisition is initialization: tie each resource to an object whose destructor releases it. Destructors run automatically when an object's lifetime ends, on every path out of a scope, in reverse order of construction. std::unique_ptr<T>, from <memory>, is RAII for one heap object. It is the sole owner, and its destructor deletes what it owns.
Predict and run
#include <iostream>
#include <memory>
int main() {
auto owner = std::make_unique<int>(25);
std::cout << *owner << "\n";
return 0;
}Check your prediction
25std::make_unique<int>(25) allocates an int, initializes it with 25 and returns the std::unique_ptr<int> that owns it. *owner reads the value. No delete appears because none is needed: when main returns, owner is destroyed, and its destructor deletes the integer. Now add auto copy = owner; and compile. The copy constructor of unique_ptr is deleted, so the compiler refuses, typically saying it calls a deleted function. Two owners of one object would mean two deletes. Remove the copy line before continuing.
Early returns without leaks
A type that reports its own lifetime shows what RAII buys. The function below leaves early on one path, and the owned object is still destroyed exactly once on both paths:
#include <iostream>
#include <memory>
#include <string>
struct Tracked {
std::string name;
explicit Tracked(std::string text) : name(std::move(text)) { std::cout << "make " << name << "\n"; }
~Tracked() { std::cout << "drop " << name << "\n"; }
};
bool check(int quantity) {
auto rule = std::make_unique<Tracked>("rule for " + std::to_string(quantity));
if (quantity < 0) {
std::cout << "reject\n";
return false;
}
std::cout << "accept\n";
return true;
}
int main() {
check(-1);
check(5);
return 0;
}make rule for -1
reject
drop rule for -1
make rule for 5
accept
drop rule for 5With a raw Tracked* rule = new Tracked(...), the early return false; would skip any delete written at the bottom, and the first object would leak. The unique_ptr version has nothing to remember. Its destructor runs after the return value is computed and before the caller sees it, which is why drop follows reject.
Ownership in function signatures
Ownership is part of an interface, and C++ signatures can say it precisely:
void install(std::unique_ptr<Rule> rule)takes ownership. The caller must writeinstall(std::move(rule)), so the transfer is visible at the call site. This is a sink.std::unique_ptr<Rule> make_rule()returns ownership. The caller now owns the result. This is a factory.bool check(const Rule& rule)borrows. It may use the object during the call, but must not keep a pointer or reference after returning.Rule* find_rule()returns a non-owning pointer that may be null. The caller must not delete it and must not use it after the owner changes.
owner.get() gives you the raw pointer for borrowing. It does not create a second owner. Calling delete on it, or wrapping it in another unique_ptr, leads to a double free when the real owner also deletes it. Holding it after the owner is reset or destroyed leaves a dangling pointer, and using that is undefined behavior:
auto owner = std::make_unique<int>(25);
int* borrowed = owner.get();
owner.reset(); // Deletes the int; owner is now empty.
std::cout << *borrowed; // Undefined behavior: the int no longer exists.Two more members change ownership and deserve care. reset() destroys the current object immediately. release() gives up ownership without destroying anything and returns the raw pointer, so the object leaks unless something else takes charge of it. You will rarely need release().
Prefer values; own dynamically when you must
Most data in this course does not need a heap owner at all. std::string, std::vector and std::map already manage their own memory, and a struct made of them needs no destructor, copy or move code of its own. That is the rule of zero: build types from members that already manage themselves, and the compiler-generated operations are correct. Reach for unique_ptr when you need an object whose concrete type is chosen at run time, an object too large or too long-lived for its scope, or a member that must stay at one address. The engine's rules are the first case.
Prefer make_unique over std::unique_ptr<T>(new T(...)). It names the type once, never leaves a moment where a raw owning pointer exists, and makes a new without a matching owner stand out in review.
Practice
Your turn
Using a Tracked type like the one above, write a factory make_rule(std::string name) that returns a std::unique_ptr<Tracked>, a borrowing function describe(const Tracked&) that prints using NAME, and a sink discard(std::unique_ptr<Tracked>) that prints discarding NAME and lets the object die when the function ends. In main, make limit and names, describe both, discard limit, then print end of main:
make limit
make names
using limit
using names
discarding limit
drop limit
end of main
drop names#include <iostream>
#include <memory>
#include <string>
#include <utility>
struct Tracked {
std::string name;
explicit Tracked(std::string text) : name(std::move(text)) { std::cout << "make " << name << "\n"; }
~Tracked() { std::cout << "drop " << name << "\n"; }
};
int main() {
// Write the factory, borrow and sink, then call them in order.
return 0;
}Hint 1: the idea
The signature carries the ownership: return unique_ptr to give it, take const Tracked& to borrow, take unique_ptr by value to receive it.
Hint 2: a first step
Call the borrow as describe(*limit), which dereferences the owner, and the sink as discard(std::move(limit)).
Show one solution
#include <iostream>
#include <memory>
#include <string>
#include <utility>
struct Tracked {
std::string name;
explicit Tracked(std::string text) : name(std::move(text)) { std::cout << "make " << name << "\n"; }
~Tracked() { std::cout << "drop " << name << "\n"; }
};
std::unique_ptr<Tracked> make_rule(std::string name) {
return std::make_unique<Tracked>(std::move(name));
}
void describe(const Tracked& rule) { std::cout << "using " << rule.name << "\n"; }
void discard(std::unique_ptr<Tracked> rule) {
std::cout << "discarding " << rule->name << "\n";
}
int main() {
auto limit = make_rule("limit");
auto names = make_rule("names");
describe(*limit);
describe(*names);
discard(std::move(limit));
std::cout << "end of main\n";
return 0;
}make limit
make names
using limit
using names
discarding limit
drop limit
end of main
drop namesThe discard parameter became the owner, so limit's object died when that parameter went out of scope, before end of main. names was never transferred and died with main. After the move, limit in main is an empty unique_ptr, a guarantee the standard gives for this type. The next lesson looks closely at moves: what std::move actually does, and what a moved-from object may be used for.
Completion is saved in this browser only. It does not measure mastery.