Facebook Pixel

You are on level: Student

0%
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section

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 SharedPtr sharing 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 no WeakPtr exists, so it stays 0.

What to implement

  • Write the class templates SharedPtr<T> and WeakPtr<T> at global scope, plus the function template MakeShared<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 ControlBlock struct holding the two counts, and the private members ptr_ and cb_.
  • You may add members, helper types, and functions, and change ControlBlock and the private members as you like, since the driver never touches them.
  • <new>, <utility>, and <type_traits> are already included, so std::move, std::exchange, std::swap, and std::forward are available. #include any 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 SharedPtr adds one to the strong count.
  • Releasing an owner subtracts one. A release happens in the destructor, in reset, and in assignment over a non-empty SharedPtr.
  • When the strong count reaches 0, the object is destroyed (for a make object, delete on the pointer). Then, if the weak count is also 0, the control block is freed. The object always dies first.
  • A moved SharedPtr hands its reference to the destination, so a move changes no count.
  • Everything here runs on one thread, so plain integers are enough. std::shared_ptr updates its counts with atomic instructions so that copies on different threads stay correct.

Memory as the driver sees it

  • Allocate with new and free with delete. The driver sees memory only through the global operator new and operator delete, and it calls every allocation your code makes a block.
  • When your code frees a block, the driver prints block id freed. id is the object id of the command that allocated it (make s id, reset s id, or makeshared 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 dtor or block line for the same id instead of a crash.
  • Tracked's destructor never touches a SharedPtr or WeakPtr.

Commands

  • Each command is one line. Slots are named by one lowercase letter.
  • A slot is absent, holds one SharedPtr<Tracked>, or holds one WeakPtr<Tracked> (Part 2). A SharedPtr or WeakPtr may be empty.
  • Ids are positive integers, each used for one Tracked object per test.
  • Every command is valid for the slots it names: a copy or move never mixes the two kinds.
CommandWhat the driver runsPrints
make sSharedPtr<Tracked> s;nothing
make s idSharedPtr<Tracked> s(new Tracked(id));ctor id
copy d sIf d is absent, SharedPtr<Tracked> d(s);. Otherwise d = s;, a self-assignment when d and s are the same slot.events
move d sIf 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 ids.reset(); or s.reset(new Tracked(id));, constructing the Tracked firstevents
get ss.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 ss.use_count()use_count s n
drop ss goes out of scope: its destructor runs and the slot becomes absent.events
allocsCounts 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

  1. Implement SharedPtr with the members below.
  2. The driver queries slots through const references, so the last five members must be const.
  3. Both move operations must be noexcept, and the T* constructor and operator bool must be explicit. The driver checks these at compile time, and in later parts the return types of lock and MakeShared. A failed check is a compile error in driver.cpp (the hidden driver) whose message names the rule.
  4. reset(p) with p == get() is outside the contract, and no test does it.
  5. A correct class makes exactly one allocation in SharedPtr(T*) and in reset(p), the control block, and none anywhere else. So each make s id adds 2 to allocs: the driver's Tracked and your block.
MemberContractCalled 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) noexceptTakes other's reference and leaves other empty.move d s into an absent d; lock
SharedPtr& operator=(SharedPtr&& other) noexceptReleases 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() constThe owned object, or nullptr.get s, lock
long use_count() constThe strong count, or 0 when empty.use_count s
T& operator*() const and T* operator->() constThe owned object. Never called on an empty SharedPtr.get s
explicit operator bool() consttrue when not empty.get s

Output: the events are Tracked lines and block lines.

ctor id
dtor id
block id freed
  • Tracked prints ctor id when it is constructed and dtor id when it is destroyed. The block line is described above.
  • Tracked would print copy id or move id if 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 a copy, move, or lock into 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:

  1. A WeakPtr points at the same control block and counts in the weak count, never in the strong count, so it cannot keep the object alive.
  2. It does keep the control block alive: the block is freed only when both counts are 0.
  3. 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.
  4. Releasing an observer subtracts one from the weak count. If that leaves both counts at 0, the block is freed.
  5. The driver queries WeakPtrs through const references too.
MemberContractCalled 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) noexceptTakes 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() constThe strong count of the observed object: 0 when the object is gone or the WeakPtr is empty.use_count w
bool expired() constuse_count() == 0.expired w
SharedPtr<T> lock() constA 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:

CommandWhat the driver runsPrints
weak w sWeakPtr<Tracked> w(s); for an absent w and a SharedPtr slot snothing
copy d w and move d wAs in Part 1, with WeakPtr copy or move construction into an absent d and assignment into a present oneevents
reset ww.reset();events
expired ww.expired()expired w true or expired w false
lock d wIf 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.

  1. MakeShared<T>(args...) makes a single allocation that holds both the control block and the object. It constructs the object inside it and returns a SharedPtr<T> that owns the object with a strong count of 1.
  2. When the strong count of a MakeShared object reaches 0, run its destructor without freeing anything. The memory goes when the whole block is freed, after the last WeakPtr releases it.
  3. A test can hold both kinds of block at once, and every member from Parts 1 and 2 must work with either.
  4. A correct MakeShared makes exactly one allocation, so each makeshared s id adds 1 to allocs. Its block line reads block id freed like any other.

Three tools build the object in memory you already own, and one passes the arguments on:

ToolWrittenWhat it does
Storage for one T inside a structalignas(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 callp->~T()ends the object's lifetime without freeing its memory
Perfect forwardingT(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:

CommandWhat the driver runsPrints
makeshared s idSharedPtr<Tracked> s(MakeShared<Tracked>(id)); for an absent sctor id

Tests 8–9 cover this part.

Example
Input
6
make a 1
copy b a
use_count a
reset a 2
drop b
allocs
Output
ctor 1
use_count a 2
ctor 2
dtor 1
block 1 freed
allocs 4
end
dtor 2
block 2 freed
Explanation

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.