UniquePtr with a Custom Deleter
Prerequisites: RAII: Cleanup That Happens Automatically, Raw Pointers, unique_ptr, shared_ptr, and weak_ptr, Move Semantics Without Magic, Object Lifetime: When C++ Objects Begin and End
A feed handler allocates one OrderBook per symbol on the heap and hands each book between components during the day. Exactly one component may free a given book, exactly once, whichever way control leaves the code that holds it.
std::unique_ptr puts that rule into a type. Build a smaller version of it.
What to implement
- Write the class template
UniquePtr<T, Deleter>at global scope. You write only the class. - A hidden driver instantiates it as
UniquePtr<Tracked>, runs it through a list of commands, and prints what happened.Trackedis a driver type that reports its own construction and destruction. - The editor already declares every member the driver calls, plus
DefaultDelete<T>, a deleter whoseoperator()runsdelete p. <utility>is already included, sostd::moveandstd::exchangeare available.#includeany other header you need at the top of your code.- On stdin, the first line is the number of commands, and each remaining line is one command.
- There are two parts. One solution must pass all ten tests.
The class
A UniquePtr is either empty (it holds nullptr) or owns one object. Destroying the owned object means calling the stored deleter on its pointer, deleter_(ptr_), never delete directly: Part 2 replaces the deleter, and the same code must keep working.
| Member (Part 1) | Contract | Called by |
|---|---|---|
UniquePtr() | Empty. | make s |
explicit UniquePtr(T* p) | Owns p. | make s id |
UniquePtr(const UniquePtr&) = delete and operator=(const UniquePtr&) = delete | Copying does not compile. | compile-time check |
UniquePtr(UniquePtr&& other) noexcept | Takes other's pointer and leaves other empty. | move d s into an absent d |
UniquePtr& operator=(UniquePtr&& other) noexcept | Destroys the object *this owned, if any, takes other's pointer, and leaves other empty. Assigning a UniquePtr to itself changes nothing. | move d s into a present d |
~UniquePtr() | Destroys the owned object, if any. | drop s, end of input |
T* get() const | The stored pointer, or nullptr. | get s, deref s, watch s |
T* release() | Returns the pointer and leaves *this empty, destroying nothing. The caller now owns the object. | release s |
void reset(T* p = nullptr) | Stores p first, then destroys the previously owned object, if any. | reset s, reset s id |
T& operator*() const and T* operator->() const | The owned object. Never called on an empty pointer. | deref s |
explicit operator bool() const | true when not empty. | bool s |
reset(p)withp == get()andp != nullptris outside the contract, and no test does it.- The driver queries slots through
constreferences, soget,operator*,operator->, andoperator boolmust beconstmembers. - The driver checks at compile time that
UniquePtr<Tracked>cannot be copied, that both move operations arenoexcept, and that theT*constructor andoperator boolareexplicit. A failed check is a compile error indriver.cpp(the hidden driver) whose message names the rule.
Commands
- Each command is one line. Slots are named by one lowercase letter.
- A slot is either absent or holds one
UniquePtr, which may be empty. - Ids are positive integers, each used for one
Trackedobject per test. Every command is valid for the slots it names.
| Command | What the driver runs | Prints |
|---|---|---|
make s | UniquePtr<Tracked> s; | nothing |
make s id | UniquePtr<Tracked> s(new Tracked(id)); | ctor id |
move d s | If d is absent, UniquePtr<Tracked> d(std::move(s));. Otherwise d = std::move(s);, a self-move when d and s are the same slot. | events |
reset s or reset s id | s.reset(); or s.reset(new Tracked(id));, constructing the Tracked first | events |
release s | Tracked* p = s.release();. The driver keeps p and deletes it at the end. | release s id or release s null |
get s | s.get() | get s id or get s null |
bool s | static_cast<bool>(s) | bool s true or bool s false |
deref s | *s and s->, which must both reach the object get() returns | deref s id |
drop s | s goes out of scope: its destructor runs and the slot becomes absent. | events |
watch s | From now on, every dtor line also shows what s holds at that moment. | nothing |
allocs | Counts the heap allocations made inside UniquePtr members so far. | allocs n |
- A later
watchreplaces the current one, and droppingsturns it off. allocsdoes not count the driver's ownnew Tracked.
Events
A Tracked that is | Prints |
|---|---|
| constructed | ctor id |
| destroyed | dtor id, or while a slot is watched, dtor id (s holds k) or dtor id (s empty) |
| copied or moved | copy id or move id, which a correct UniquePtr never causes, since it moves pointers, not objects |
The driver never returns memory to the system, so freeing an object twice shows up as a second dtor line for the same id instead of a crash.
End of input
- The driver prints
endand turns off anywatch. - The remaining slots go out of scope in reverse order of creation, the way local variables die at a closing brace. A slot is created by
make, bymakewith(Part 2), or bymoveinto an absent slot. - Last, the driver deletes the pointers it took with
release, oldest first, using plaindelete.
The tests observe the order inside reset through watch. They do not observe whether move assignment destroys the old object before or after it stores the new pointer, so either order passes.
Part 1: Sole ownership
Implement the members in the table above. A correct class allocates nothing, so every allocs line prints allocs 0.
Tests 1–7 cover this part and use only UniquePtr<Tracked> with DefaultDelete.
Part 2: A custom deleter
A deleter is any object with an operator()(T*) that frees the object. The UniquePtr stores one next to the pointer and calls it wherever Part 1 destroyed an object.
- The driver's
LogDeletercarries a name. Calling it printsdeleter name frees idand then deletes the object, which printsdtor id. - Copying or moving a
LogDeletercopies its name.
| Member | Contract | Called by |
|---|---|---|
UniquePtr(T* p, Deleter d) | Owns p (which may be nullptr) and stores d. | makewith |
Deleter& get_deleter() | The stored deleter. | getdeleter s |
The deleter belongs to the pointer it frees:
- The move constructor moves
other's deleter along with the pointer. - Move assignment frees
*this's old object with*this's old deleter, then takes both the pointer and the deleter fromother. releasedoes not call the deleter.
| Command | What the driver runs | Prints |
|---|---|---|
makewith s name | UniquePtr<Tracked, LogDeleter> s(nullptr, LogDeleter(name)); | nothing |
makewith s name id | UniquePtr<Tracked, LogDeleter> s(new Tracked(id), LogDeleter(name)); | ctor id |
getdeleter s | s.get_deleter() | getdeleter s name |
Every Part 1 command also works on these slots. A move never mixes the two kinds.
Tests 8–10 cover this part.
6 make a 1 make b 2 move b a get a reset b 3 release b
ctor 1 ctor 2 dtor 2 get a null ctor 3 dtor 1 release b 3 end dtor 3
move b a is a move assignment because slot b already exists. b takes object 1, a is left empty, and b's old object 2 is destroyed during the assignment.
reset b 3 constructs object 3, stores it in b, and then destroys object 1. release b hands object 3 back without destroying it.
At the end both slots are empty, so their destructors free nothing, and the driver deletes the released object 3 itself.