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.#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.
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 toN.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 toalignof(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 aTat addressp, in memory the caller already owns, returns aT*to it, and never allocates. - Its counterpart is an explicit destructor call,
q->~T(), which runsT's destructor and frees nothing. delete qwould also hand the memory back to the allocator, which is wrong for an object insidebuf_.
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 andconstfromF, giving the type to store, calledTbelow.std::forward<F>(f)(from<utility>) passesfon as the same kind of value it arrived as, soT(std::forward<F>(f))moves from an rvalue and copies from an lvalue.- The
requiresline under the template stops the compiler from choosing this constructor when the argument is itself aSmallFunction. 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
structof 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 forT; - 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:
sizeof(T) <= 32alignof(T) <= alignof(std::max_align_t)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 newandoperator deletecalls (every form) made insideSmallFunctionmembers. - So use
newanddeletefor the heap block, notmallocandfree.
| Member (Part 1) | Contract | Called 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() const | true 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:
makeandemptyname absent slots, every other command names present slots, andcallnames only non-empty ones.
| Command | What the driver runs | Prints |
|---|---|---|
make s kind id | Builds 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 s | SmallFunction<long long(long long)> s; | nothing |
call s x | s(x) | call s r, where r is the result |
bool s | static_cast<bool>(s) | bool s true or bool s false |
drop s | s goes out of scope: its destructor runs and the slot becomes absent. | events |
heap | Reads 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, byempty, or (in Part 2) bycopyormoveinto 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:
| Kind | sizeof | alignof | Move constructor | Stored |
|---|---|---|---|---|
small | 16 | 8 | noexcept | inline |
exact | 32 | 8 | noexcept | inline |
big | 40 | 8 | noexcept | heap |
risky | 16 | 8 | may throw | heap |
wide | 32 | 32 (alignas(32)) | noexcept | heap |
A Tracked that is | Prints |
|---|---|
| constructed | ctor id |
| copied | copy id |
| moved | move id |
| destroyed | dtor 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
Trackedis. Somakealways printsctor id, thenmove idas the constructor movesfinto storage, thendtor id (moved-from)as the localfdies. heapprints how manyoperator newandoperator deletecallsSmallFunctionmembers have made since the test began. The driver's own work, such as building the local callable formakeor 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
dtorline 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
smallandexactcallables printsheap 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:
| Member | Contract | Called 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) noexcept | Takes 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) noexcept | If 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.
| Command | What the driver runs | Prints |
|---|---|---|
copy d s | If 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 s | If 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.
7 make a small 1 make b big 2 call a 5 call b 7 call a 4 drop b heap
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
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.