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

Small-Buffer Callable

Prerequisites: Type Erasure with std::function and std::any, Allocation in the Hot Path, Virtual Functions and Vtables

A feed handler keeps one callback per subscription and calls it for every MarketUpdate on that symbol. std::function gives callables of any size one type, but whether constructing one allocates depends on a library buffer size the code never shows.

Build SmallFunction, whose storage rule is fixed and stated: a callable that fits a 32-byte buffer inside the object never touches the heap, and any other callable takes exactly one heap block.

What to implement

  • Write the class template SmallFunction<R(Args...)> at global scope. You write only the class.
  • A hidden driver instantiates it as SmallFunction<long long(long long)>, stores callables of several sizes in it, runs a list of commands, and prints what happened. The editor already declares every member the driver calls.
  • Do not use std::function, std::any, or virtual functions: the task is to build their mechanism by hand.
  • <new>, <cstddef>, <type_traits>, and <utility> are already included. #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 two parts. One solution must pass all ten tests.

Tools the class needs

These pieces of C++ have not appeared in Module 1 yet.

Alignment, as in the padding rules from Copies, Moves, and Object Layout:

  • Every type has an alignment, alignof(T), and its objects must start at an address that is a multiple of it. alignof(std::int64_t) is 8.
  • alignas(N) on a declaration raises its alignment to N.
  • alignof(std::max_align_t) is the strictest alignment any built-in type needs (8 or 16 on 64-bit platforms).
  • The starter declares alignas(std::max_align_t) unsigned char buf_[kBufferSize];: 32 raw bytes that can hold any type with an alignment up to alignof(std::max_align_t).

Placement new. new T(args) asks the allocator for memory, then constructs a T in it.

  • Placement new, written ::new (static_cast<void*>(p)) T(args), does only the second step. It constructs a T at address p, in memory the caller already owns, returns a T* to it, and never allocates.
  • Its counterpart is an explicit destructor call, q->~T(), which runs T's destructor and frees nothing.
  • delete q would also hand the memory back to the allocator, which is wrong for an object inside buf_.

The converting constructor template <class F> SmallFunction(F&& f) takes the templated callable parameter from the type erasure article.

  • std::decay_t<F> (from <type_traits>) removes references and const from F, giving the type to store, called T below.
  • std::forward<F>(f) (from <utility>) passes f on as the same kind of value it arrived as, so T(std::forward<F>(f)) moves from an rvalue and copies from an lvalue.
  • The requires line under the template stops the compiler from choosing this constructor when the argument is itself a SmallFunction. Leave it in place.

The ops table. The type erasure article shows std::function operating on its callable through stored function pointers, invoke_fn and manager_fn. A vtable is the compiler's version: one static table of function pointers per class, and one pointer to it in each object.

Your class needs a hand-written table of this kind, an ops table:

  • a struct of function pointers for every operation that depends on the stored type (call, copy, move, destroy);
  • one static instance per stored type T, filled in with function templates instantiated for T;
  • in each object, a pointer to its type's table. A null pointer can mean empty.

The functions receive the callable as a void*, and static_cast<T*>(p) turns it back into the T* it came from. std::is_nothrow_move_constructible_v<T> is true when T's move constructor is declared unable to throw.

The class

A SmallFunction is either empty or stores one callable. The callable is stored inline, constructed in buf_ with placement new, when all three hold:

  1. sizeof(T) <= 32
  2. alignof(T) <= alignof(std::max_align_t)
  3. std::is_nothrow_move_constructible_v<T>

Otherwise it goes on the heap, in one block created by new T(...) and released by delete.

  • The driver counts the operator new and operator delete calls (every form) made inside SmallFunction members.
  • So use new and delete for the heap block, not malloc and free.
Member (Part 1)ContractCalled by
SmallFunction()Empty.empty s
template <class F> SmallFunction(F&& f)Stores a std::decay_t<F> constructed from std::forward<F>(f), inline or on the heap by the storage rule.make s kind id
R operator()(Args... args)Calls the stored callable with args and returns its result. Never called on an empty object.call s x
explicit operator bool() consttrue when not empty.bool s
~SmallFunction()Destroys the stored callable, if any, and releases its heap block if it has one.drop s, end of input

The driver checks at compile time that kBufferSize is still 32, the class can be copied, both move operations are noexcept, and operator bool is explicit. A failed check is a compile error in driver.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 SmallFunction<long long(long long)>, which may be empty. Ids are positive integers.
  • Every command is valid for the slots it names: make and empty name absent slots, every other command names present slots, and call names only non-empty ones.
CommandWhat the driver runsPrints
make s kind idBuilds a local callable f of the given kind holding Tracked(id), runs SmallFunction<long long(long long)> s(std::move(f));, then lets f go out of scope.events
empty sSmallFunction<long long(long long)> s;nothing
call s xs(x)call s r, where r is the result
bool sstatic_cast<bool>(s)bool s true or bool s false
drop ss goes out of scope: its destructor runs and the slot becomes absent.events
heapReads the driver's counters.heap allocs A frees F

End of input: the driver prints end. The remaining slots then go out of scope in reverse order of creation, like local variables at a closing brace.

  • A slot is created by make, by empty, or (in Part 2) by copy or move into an absent slot.

Callables and events

Every callable holds a Tracked and a running total that starts at 0. Calling it with x adds x to its total and returns the new total. The five kinds differ only in layout, which decides where SmallFunction stores them:

KindsizeofalignofMove constructorStored
small168noexceptinline
exact328noexceptinline
big408noexceptheap
risky168may throwheap
wide3232 (alignas(32))noexceptheap
A Tracked that isPrints
constructedctor id
copiedcopy id
movedmove id
destroyeddtor id, or dtor id (moved-from) if it has been moved from
assigned (a correct class never assigns one callable to another)copy-assign id or move-assign id
  • A callable is copied or moved exactly when its Tracked is. So make always prints ctor id, then move id as the constructor moves f into storage, then dtor id (moved-from) as the local f dies.
  • heap prints how many operator new and operator delete calls SmallFunction members have made since the test began. The driver's own work, such as building the local callable for make or recording a report line, is not counted.
  • The driver never returns memory to the system, so releasing a block twice shows up as an extra dtor line and an extra free instead of a crash.

Part 1: Store, call, destroy

Implement the default constructor, the converting constructor, operator(), operator bool, and the destructor.

  • Inline callables allocate nothing, so a test that stores only small and exact callables prints heap allocs 0 frees 0.
  • Part 1 tests never copy or move a SmallFunction, so the Part 2 members can keep their empty bodies until then.

Tests 1–4 cover this part and use only the commands above.

Part 2: Copy and move

A cloned strategy copies its subscriptions, and a handler that reorganizes its tables moves them. Implement the remaining four members:

MemberContractCalled by
SmallFunction(const SmallFunction& other)Stores a copy of other's callable, with the same storage as other.copy d s into an absent d
SmallFunction(SmallFunction&& other) noexceptTakes other's callable and leaves other empty.move d s into an absent d
SmallFunction& operator=(const SmallFunction& other)If other is *this, does nothing. Otherwise destroys the current callable, if any, then copies other's callable in as the copy constructor does.copy d s into a present d
SmallFunction& operator=(SmallFunction&& other) noexceptIf other is *this, does nothing. Otherwise destroys the current callable, if any, then takes other's callable as the move constructor does, leaving other empty.move d s into a present d
  • Copying: a heap callable's copy gets a new block of its own. A copy of an empty object is empty. A copy has its own running total, starting from the source's current total.
  • Moving: an inline callable is move-constructed into this object's buffer, and then the moved-from callable in other's buffer is destroyed. A heap callable is not touched: only the pointer to its block changes hands.
CommandWhat the driver runsPrints
copy d sIf d is absent, SmallFunction<long long(long long)> d(s);. Otherwise d = s;, a self-assignment when d and s are the same slot.events
move d sIf d is absent, SmallFunction<long long(long long)> d(std::move(s));. Otherwise d = std::move(s);, a self-move when d and s are the same slot.events

Tests 5–10 cover this part.

Example
Input
7
make a small 1
make b big 2
call a 5
call b 7
call a 4
drop b
heap
Output
ctor 1
move 1
dtor 1 (moved-from)
ctor 2
move 2
dtor 2 (moved-from)
call a 5
call b 7
call a 9
dtor 2
heap allocs 1 frees 1
end
dtor 1
Explanation

Each make prints three events: the driver constructs the local callable, the converting constructor moves it into storage, and the local's moved-from shell is destroyed.

The 16-byte small callable fits, so it is constructed in a's buffer with placement new. The 40-byte big callable does not, so b allocates one heap block for it.

call a 4 returns 9 because a's total was already 5. Dropping b destroys its callable and releases the block: one allocation, one free.

At the end of the input a goes out of scope and destroys its inline callable, which frees nothing.