"The rules are cleaned up" is easy to claim and hard to see. A leak prints nothing, a double free may print nothing until much later, and a destructor that never runs looks exactly like one that runs and does nothing. This checkpoint turns lifetime into a number you can assert. Each tracked rule increments a counter when it is constructed and decrements it when it is destroyed, so the counter is the number of live rules at any moment. Then you move rules between owners, erase one, and check the number at every step. The project's own test suite uses the same technique with a CountingRule.
Predict and run
#include <iostream>
#include <memory>
struct Tracked {
explicit Tracked(int& live) : live_(live) { ++live_; }
~Tracked() { --live_; }
int& live_;
};
int main() {
int live = 0;
{ auto owner = std::make_unique<Tracked>(live); std::cout << live << "\n"; }
std::cout << live << "\n";
return 0;
}Check your prediction
1
0The inner braces form a scope, and owner dies at the closing brace, which runs ~Tracked and brings the count back to 0. Notice where live is declared: outside the scope that owns the tracked object. Each Tracked keeps a reference to the counter and writes through it in its destructor. If the counter died first, that write would go to a dead object, which is undefined behavior. A borrowed reference is only safe while its target outlives the borrower, and here that ordering is guaranteed by declaring the counter first: locals are destroyed in reverse order of declaration.
What you will use
- A polymorphic base with a virtual destructor.
Rulehas a pureacceptsandvirtual ~Rule() = default;, so deleting throughstd::unique_ptr<Rule>runs the derived destructor. - A tracked derived rule.
Trackedincrements a borrowed counter in its constructor and decrements it in its destructor, markedoverride. - Owners that change. A
std::vector<std::unique_ptr<Rule>>, a separatestd::unique_ptr<Rule>that receives a move, anderase, which destroys an element. - A guaranteed moved-from state. A moved-from
unique_ptris null, so the empty slot in the vector can be tested.
Plan before you type
- Declare
int live = 0;before the scope that holds the rules. - Inside a new scope, push two tracked rules into a vector and print the count.
- Move the first element into a separate owner. The count must not change: a move transfers, it neither copies nor destroys. Print the count and whether the vector slot is now empty.
- Erase the second element. That destroys it, so the count drops by one.
- Let the scope end, which destroys the vector, its empty slot and the separate owner. Print the count after the closing brace.
Prove it can fail
Once the output matches, break the solution in two ways and restore it after each. First, delete the --live_; from ~Tracked: the last two lines become erased: live 2 and scope ended: live 2, which is exactly what a rule that is never destroyed would look like. Second, remove virtual from ~Rule(). The build now fails: ~Tracked() override claims to override a virtual destructor that no longer exists, so the compiler stops with error: only virtual member functions can be marked 'override'. That is override doing its job, catching the broken base before anything is deleted through it. Now also remove override from ~Tracked(). The program builds with only a -Wdelete-abstract-non-virtual-dtor warning (which -Werror would refuse) and runs, and the derived destructors are skipped: erased: live 2 and scope ended: live 2, as if no rule were ever destroyed. Formally, it is undefined behavior. Restore both keywords.
Mistakes worth checking for
- The count goes up to 3 after the move. The code copied instead of moving, for example by constructing a new
Trackedfrom the old one. Aunique_ptrcannot be copied, so look for amake_uniquethat rebuilds the object. - The count drops during the move. The code called
reset()orrelease()on the source and recreated the rule, or destroyed the receiving owner early. Move withstd::unique_ptr<Rule> kept = std::move(rules[0]);. rules.size()is 1 after the move. It is still 2: moving from an element leaves an emptyunique_ptrin its slot. Onlyeraseremoves slots. Code that later loops overrulesmust skip or remove null entries.- The program crashes or prints garbage at the end. The counter was declared inside the same scope as the rules, after them, so it died first.
error: allocating an object of abstract class type.Tracked::acceptsdoes not exactly match the base signature, usually a missingconst. Mark itoverrideto get a clearer message.
Practice
Your turn
Write Rule and a final Tracked rule that counts live instances and accepts every quantity. Follow the plan and print:
installed: live 2
moved: live 2, slot empty 1
erased: live 1
kept rule accepts 5: 1
scope ended: live 0#include <iostream>
#include <memory>
#include <utility>
#include <vector>
class Rule {
public:
virtual ~Rule() = default;
virtual bool accepts(int quantity) const = 0;
};
int main() {
int live = 0;
{
// Install two tracked rules, move one, erase the other.
}
std::cout << "scope ended: live " << live << "\n";
return 0;
}Hint 1: the idea
Only construction and destruction change the counter. A move changes which owner is responsible, and nothing else.
Hint 2: a first step
Start with Tracked: a Rule that holds a reference to the counter, adds one when it is built and subtracts one when it is destroyed. Build one in a nested scope and print the counter inside and after it: 1, then 0. Only then put rules in the vector.
Show one solution
#include <iostream>
#include <memory>
#include <utility>
#include <vector>
class Rule {
public:
virtual ~Rule() = default;
virtual bool accepts(int quantity) const = 0;
};
class Tracked final : public Rule {
public:
explicit Tracked(int& live) : live_(live) { ++live_; }
~Tracked() override { --live_; }
bool accepts(int) const override { return true; }
private:
int& live_;
};
int main() {
int live = 0;
{
std::vector<std::unique_ptr<Rule>> rules;
rules.push_back(std::make_unique<Tracked>(live));
rules.push_back(std::make_unique<Tracked>(live));
std::cout << "installed: live " << live << "\n";
std::unique_ptr<Rule> kept = std::move(rules[0]);
std::cout << "moved: live " << live << ", slot empty " << (rules[0] == nullptr) << "\n";
rules.erase(rules.begin() + 1);
std::cout << "erased: live " << live << "\n";
std::cout << "kept rule accepts 5: " << kept->accepts(5) << "\n";
}
std::cout << "scope ended: live " << live << "\n";
return 0;
}installed: live 2
moved: live 2, slot empty 1
erased: live 1
kept rule accepts 5: 1
scope ended: live 0Every line pins one ownership fact: two objects exist, a move preserved both, erasing destroyed exactly one, and the end of the scope destroyed the rest through the base pointer. The counter checks behavior that the type system cannot, because a missing destructor call is not a type error. On Day 6 you will pair it with compile-time checks of the types themselves. Day 3 now turns to the other kind of polymorphism: templates that accept any suitable callable.
Completion is saved in this browser only. It does not measure mastery.