SharedPtr and WeakPtr
Prerequisites: Raw Pointers, unique_ptr, shared_ptr, and weak_ptr, Object Lifetime: When C++ Objects Begin and End, RAII: Cleanup That Happens Automatically, Move Semantics Without Magic
A market-data service shares the AAPL OrderBook with a strategy, a risk monitor, and a logger; any of them may finish last. Build small versions of std::shared_ptr, which counts owners and frees the book at zero, and std::weak_ptr, which observes it without keeping it alive.
- Control block: a small heap object, allocated separately from the pointers, that every
SharedPtrsharing an object points at. It holds two counts. - Strong count: the number of
SharedPtrs that own the object. - Weak count: the number of
WeakPtrs that observe it. In Part 1 noWeakPtrexists, so it stays 0.
What to implement
- Write the class templates
SharedPtr<T>andWeakPtr<T>at global scope, plus the function templateMakeShared<T>in Part 3. You write only these. - A hidden driver instantiates them with
Tracked, a driver type that reports its own construction and destruction, runs them through a list of commands, and prints what happened. - The editor already declares every member the driver calls, a
ControlBlockstruct holding the two counts, and the private membersptr_andcb_. - You may add members, helper types, and functions, and change
ControlBlockand the private members as you like, since the driver never touches them. <new>,<utility>, and<type_traits>are already included, sostd::move,std::exchange,std::swap, andstd::forwardare 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 three parts. One solution must pass all ten tests.
Counting rules
A SharedPtr either is empty or owns an object together with every other SharedPtr that shares it.
- Copying a
SharedPtradds one to the strong count. - Releasing an owner subtracts one. A release happens in the destructor, in
reset, and in assignment over a non-emptySharedPtr. - When the strong count reaches 0, the object is destroyed (for a
makeobject,deleteon the pointer). Then, if the weak count is also 0, the control block is freed. The object always dies first. - A moved
SharedPtrhands its reference to the destination, so a move changes no count. - Everything here runs on one thread, so plain integers are enough.
std::shared_ptrupdates its counts with atomic instructions so that copies on different threads stay correct.
Memory as the driver sees it
- Allocate with
newand free withdelete. The driver sees memory only through the globaloperator newandoperator delete, and it calls every allocation your code makes a block. - When your code frees a block, the driver prints
block id freed.idis the object id of the command that allocated it (make s id,reset s id, ormakeshared s id). - A block allocated by any other command is labeled
?, which a correct class never produces. - The driver never returns memory to the system, so freeing something twice shows up as a second
dtororblockline for the same id instead of a crash. Tracked's destructor never touches aSharedPtrorWeakPtr.
Commands
- Each command is one line. Slots are named by one lowercase letter.
- A slot is absent, holds one
SharedPtr<Tracked>, or holds oneWeakPtr<Tracked>(Part 2). ASharedPtrorWeakPtrmay be empty. - Ids are positive integers, each used for one
Trackedobject per test. - Every command is valid for the slots it names: a
copyormovenever mixes the two kinds.
| Command | What the driver runs | Prints |
|---|---|---|
make s | SharedPtr<Tracked> s; | nothing |
make s id | SharedPtr<Tracked> s(new Tracked(id)); | ctor id |
copy d s | If d is absent, SharedPtr<Tracked> d(s);. Otherwise d = s;, a self-assignment when d and s are the same slot. | events |
move d s | If d is absent, SharedPtr<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 |
get s | s.get(), static_cast<bool>(s), and, when the pointer is not null, *s and s-> | get s id or get s null when they agree, get s mismatch otherwise |
use_count s | s.use_count() | use_count s n |
drop s | s goes out of scope: its destructor runs and the slot becomes absent. | events |
allocs | Counts the heap allocations made so far: the driver's new Tracked in make s id and reset s id, and every allocation inside your code. | allocs n |
Part 1: Shared ownership
- Implement
SharedPtrwith the members below. - The driver queries slots through
constreferences, so the last five members must beconst. - Both move operations must be
noexcept, and theT*constructor andoperator boolmust beexplicit. The driver checks these at compile time, and in later parts the return types oflockandMakeShared. A failed check is a compile error indriver.cpp(the hidden driver) whose message names the rule. reset(p)withp == get()is outside the contract, and no test does it.- A correct class makes exactly one allocation in
SharedPtr(T*)and inreset(p), the control block, and none anywhere else. So eachmake s idadds 2 toallocs: the driver'sTrackedand your block.
| Member | Contract | Called by |
|---|---|---|
SharedPtr() | Empty: no object, no control block. | make s |
explicit SharedPtr(T* p) | Owns p, which is never null, with a new control block whose strong count is 1. | make s id |
SharedPtr(const SharedPtr& other) | Shares other's object, if any. | copy d s into an absent d |
SharedPtr& operator=(const SharedPtr& other) | Releases what *this owned and shares other's object. Assigning a SharedPtr to itself changes nothing. | copy d s into a present d |
SharedPtr(SharedPtr&& other) noexcept | Takes other's reference and leaves other empty. | move d s into an absent d; lock |
SharedPtr& operator=(SharedPtr&& other) noexcept | Releases what *this owned, takes other's reference, and leaves other empty. A self-move changes nothing. | move d s into a present d; lock |
~SharedPtr() | Releases what it owns, if anything. | drop s, end of input |
void reset() | Releases what it owns and becomes empty. | reset s |
void reset(T* p) | Releases what it owned and owns p with a new control block. | reset s id |
T* get() const | The owned object, or nullptr. | get s, lock |
long use_count() const | The strong count, or 0 when empty. | use_count s |
T& operator*() const and T* operator->() const | The owned object. Never called on an empty SharedPtr. | get s |
explicit operator bool() const | true when not empty. | get s |
Output: the events are Tracked lines and block lines.
ctor id
dtor id
block id freed
Trackedprintsctor idwhen it is constructed anddtor idwhen it is destroyed. Theblockline is described above.Trackedwould printcopy idormove idif it were copied or moved. A correct class never causes that, since it copies pointers, not objects.- After the last command the driver prints
end. The remaining slots then go out of scope in reverse order of creation, the way local variables die at a closing brace. - A slot is created by
make,makeshared,weak, or acopy,move, orlockinto an absent slot.
Tests 1–4 cover this part.
Part 2: Weak observers
A WeakPtr observes an object owned by SharedPtrs without owning it. Implement WeakPtr, and make SharedPtr keep the block while observers remain:
- A
WeakPtrpoints at the same control block and counts in the weak count, never in the strong count, so it cannot keep the object alive. - It does keep the control block alive: the block is freed only when both counts are 0.
- An object can therefore be destroyed while
WeakPtrs still point at its block. They read its strong count of 0 to learn that it is gone. - Releasing an observer subtracts one from the weak count. If that leaves both counts at 0, the block is freed.
- The driver queries
WeakPtrs throughconstreferences too.
| Member | Contract | Called by |
|---|---|---|
WeakPtr(const SharedPtr<T>& s) | Observes s's object. Empty when s is empty. | weak w s |
WeakPtr(const WeakPtr& other) and WeakPtr& operator=(const WeakPtr& other) | Observes what other observes; assignment first releases what *this observed. Self-assignment changes nothing. | copy d w |
WeakPtr(WeakPtr&& other) noexcept and WeakPtr& operator=(WeakPtr&& other) noexcept | Takes over other's observation and leaves other empty; assignment first releases what *this observed. A self-move changes nothing. | move d w |
~WeakPtr() and void reset() | Release what it observes; reset leaves it empty. | drop w, end of input; reset w |
long use_count() const | The strong count of the observed object: 0 when the object is gone or the WeakPtr is empty. | use_count w |
bool expired() const | use_count() == 0. | expired w |
SharedPtr<T> lock() const | A new owner of the object (strong count plus one) while it is alive; an empty SharedPtr once it is gone. | lock d w |
These commands are new, and copy, move, reset, use_count, and drop also work on WeakPtr slots:
| Command | What the driver runs | Prints |
|---|---|---|
weak w s | WeakPtr<Tracked> w(s); for an absent w and a SharedPtr slot s | nothing |
copy d w and move d w | As in Part 1, with WeakPtr copy or move construction into an absent d and assignment into a present one | events |
reset w | w.reset(); | events |
expired w | w.expired() | expired w true or expired w false |
lock d w | If d is absent, d is move-constructed from w.lock(). Otherwise d = w.lock();, a move assignment. | events, then lock d id or lock d null |
Tests 5–7 and 10 cover this part.
Part 3: One allocation with MakeShared
make s id costs two allocations: the driver's new Tracked and your control block.
MakeShared<T>(args...)makes a single allocation that holds both the control block and the object. It constructs the object inside it and returns aSharedPtr<T>that owns the object with a strong count of 1.- When the strong count of a
MakeSharedobject reaches 0, run its destructor without freeing anything. The memory goes when the whole block is freed, after the lastWeakPtrreleases it. - A test can hold both kinds of block at once, and every member from Parts 1 and 2 must work with either.
- A correct
MakeSharedmakes exactly one allocation, so eachmakeshared s idadds 1 toallocs. Its block line readsblock id freedlike any other.
Three tools build the object in memory you already own, and one passes the arguments on:
| Tool | Written | What it does |
|---|---|---|
Storage for one T inside a struct | alignas(T) unsigned char storage[sizeof(T)]; | declares the storage |
| Placement new | ::new (static_cast<void*>(storage)) T(...) | constructs a T in that storage, allocates nothing, and returns the new object's address |
| Explicit destructor call | p->~T() | ends the object's lifetime without freeing its memory |
| Perfect forwarding | T(std::forward<Args>(args)...) | passes each of MakeShared's arguments on unchanged, as the lvalue or rvalue it was given (Module 3 covers it in depth) |
One command is new:
| Command | What the driver runs | Prints |
|---|---|---|
makeshared s id | SharedPtr<Tracked> s(MakeShared<Tracked>(id)); for an absent s | ctor id |
Tests 8–9 cover this part.
6 make a 1 copy b a use_count a reset a 2 drop b allocs
ctor 1 use_count a 2 ctor 2 dtor 1 block 1 freed allocs 4 end dtor 2 block 2 freed
copy b a makes b a second owner of object 1, so its strong count is 2. reset a 2 constructs object 2 and gives a a new control block for it. Releasing a's old reference leaves object 1 with one owner, so nothing dies.
drop b releases the last owner of object 1: the object is destroyed, and since no WeakPtr observes it, its control block is freed right after.
Four allocations happened, two objects and two control blocks. At the end a goes out of scope and object 2 and its block go the same way.