Optional Without the Heap
Prerequisites: Object Lifetime: When C++ Objects Begin and End, Move Semantics Without Magic, RAII: Cleanup That Happens Automatically, C++ Casts and Type Safety
A strategy keeps the last MarketUpdate it saw for AAPL, but before the first update there is none. std::optional<MarketUpdate> holds "maybe a value" in its own bytes, next to a flag, with no heap allocation. Build a smaller version of it.
- Engaged: an
Optional<T>that holds oneT. Otherwise it is empty. - Placement new:
::new (static_cast<void*>(storage_)) T(args)runs aTconstructor on memory you already own and returns a pointer to the new object. It allocates nothing. - Explicit destructor call:
p->~T()runs the destructor of the object atp. It frees nothing.
What to implement
- Write the class template
Optional<T>at global scope. You write only the class. - A hidden driver instantiates it as
Optional<Tracked>, runs it through a list of commands, and prints what happened.Trackedis a driver type that reports its own construction, copies, moves, assignments, and destruction. - The editor already declares every member the driver calls and the two private data members.
<new>,<utility>, and<type_traits>are already included, so placement new,std::launder,std::move,std::forward, and the type traits are 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.
Raw storage and manual lifetimes
- The value lives in a member array,
alignas(T) unsigned char storage_[sizeof(T)], next to a flag,bool engaged_. - Declaring the array constructs no
T. An emptyOptional<Tracked>must not construct aTracked, andTrackedhas no default constructor at all. alignas(T)gives the arrayT's alignment, the rule that places struct fields at aligned offsets. Without it, aTbuilt there could start at an address wrong for its type, the hazard C++ Casts and Type Safety describes for wire buffers.- In the terms of Object Lifetime, a value's lifetime begins when placement new returns and ends when
~T()runs. Outside that spanstorage_is bytes again. The compiler can't track this, so the class does. - The class keeps one invariant:
engaged_istrueexactly when a liveToccupiesstorage_.
Reaching the value
reinterpret_cast<T*>(storage_)has the right type and address, but formally it still points at the byte array, not at theTthat placement new created there.std::launder, from<new>, returns a pointer to the object that actually lives at that address. Sostd::launder(reinterpret_cast<T*>(storage_))is the fully correct form.- The reference solution uses it. It compiles to no instructions, so no test can observe whether you do.
The class
| Member | Contract | Called by |
|---|---|---|
Optional() | Empty. No T is constructed. | make s |
Optional(const T& v) | Engaged, holding a T copy-constructed from v. | make s copy id |
Optional(T&& v) | Engaged, holding a T move-constructed from v. | make s move id |
~Optional() | Destroys the held value, if any. | drop s, end of input |
template <class... Args> T& emplace(Args&&... args) | Destroys the held value, if any, then constructs a new T in storage_ from args and returns a reference to it. | emplace s ... |
void reset() | Destroys the held value, if any. Afterward the Optional is empty. | reset s |
bool has_value() const | true when engaged. | get s |
value(), operator*(), operator->() | The held value. Never called on an empty Optional. | get s |
value()andoperator*returnT&, andoperator->returnsT*. Each has aconstoverload that returnsconst T&orconst T*.- Each constructor and each
emplacebuilds exactly oneTwith one constructor call: no extra copy, no extra move, no temporary. emplaceuses two features that the editor already declares:template <class... Args>makesArgsa parameter pack, soemplaceaccepts any number of arguments of any types and hands them all toT's constructor.std::forward<Args>(args)...passes each argument on as it was at the call site. An rvalue, such as a temporary, is moved; an lvalue, such as a named variable, is copied.- Plain
args...would make every argument an lvalue, because a named parameter is an lvalue, so a temporary would be copied instead of moved.
Compile-time checks
The driver checks at compile time that:
storage_is aligned forT(using a second driver type whose alignment is 16);- the move constructor is
noexceptwheneverT's is (the editor declares it that way, for the reason in Move Semantics Without Magic); emplace,has_value, and the accessors have the return types above.
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
Optional<Tracked>, which may be empty. - Ids are positive integers. Every command is valid for the slots it names:
makenames an absent slot, and every other command names present slots.
| Command | What the driver runs | Prints |
|---|---|---|
make s | Optional<Tracked> s; | nothing |
make s copy id | Tracked t(id); Optional<Tracked> s(t);, then t goes out of scope | events |
make s move id | Optional<Tracked> s(Tracked(id)); | events |
emplace s id | s.emplace(id); | events |
emplace s copy id | Tracked t(id); s.emplace(t);, then t goes out of scope | events |
emplace s move id | s.emplace(Tracked(id)); | events |
reset s | s.reset(); | events |
get s | s.has_value(), then, if engaged, value(), *s, and s-> through both a const and a non-const reference | get s empty or get s id |
drop s | s goes out of scope: its destructor runs and the slot becomes absent. | events |
allocs | Counts the heap allocations made inside Optional members so far. | allocs n |
Part 1: Storage, emplace, and reset
- Implement the members in the class table.
- Keep
engaged_in step with the storage on every path. A value that is never destroyed is missing itsdtorline, and a value destroyed twice prints two. - A correct class allocates nothing, so every
allocsline printsallocs 0.
Output: the events come from Tracked, which holds one int id.
ctor id
copy id
move id
copyassign old from new
moveassign old from new
dtor id
ctor id: constructed from anint.copy idormove id: copy- or move-constructed.dtor id: destroyed.copyassign old from newormoveassign old from new: copy- or move-assigned. The object that heldoldnow holdsnew.- Moving from a
Trackedsets the source's id to 0, so a moved-from value prints as 0. For example,dtor 0prints when the temporary inmake s move iddies. getasks all six accessors for the value. They must return the same address, inside theOptionalobject's own bytes; otherwisegetprintsget s mismatchorget s outsideinstead of the id. A correct class never prints either.allocscounts calls to the globaloperator newmade while anOptionalmember runs, so a value kept on the heap shows up there as well.- 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, or in Part 2 bycopyormoveinto an absent slot.
Tests 1–5 cover this part.
Part 2: Copies and moves
Four more members make Optional copyable and movable. They follow the rules of std::optional.
| Member | Contract | Called by |
|---|---|---|
Optional(const Optional& other) | Empty if other is empty; otherwise holds a T copy-constructed from other's value. | copy d s into an absent d |
Optional(Optional&& other) | Empty if other is empty; otherwise holds a T move-constructed from other's value. other stays engaged, holding its moved-from value. | move d s into an absent d |
Optional& operator=(const Optional& other) | See the table below. | copy d s into a present d |
Optional& operator=(Optional&& other) | See the table below. other stays engaged if it was engaged. | move d s into a present d |
What an assignment does depends on which sides hold a value:
*this | other | Copy assignment | Move assignment |
|---|---|---|---|
| empty | empty | nothing | nothing |
| empty | engaged | copy-constructs a T from other's value in storage_ | move-constructs it |
| engaged | empty | destroys its value and becomes empty | the same |
| engaged | engaged | T's copy assignment | T's move assignment |
- Assigning an
Optionalto itself changes nothing and calls nothing on theTracked. This rule is an addition tostd::optional's. - When both sides are engaged, the existing
Tis assigned rather than destroyed and rebuilt, so the only event is onecopyassignormoveassignline. - A moved-from
Optionalis not empty. Likestd::optional, it keeps its value in the moved-from state, which forTrackedmeans id 0.
Two commands are new:
| Command | What the driver runs | Prints |
|---|---|---|
copy d s | If d is absent, Optional<Tracked> d(s);. Otherwise d = s;, a self-copy when d and s are the same slot. | events |
move d s | If d is absent, Optional<Tracked> d(std::move(s));. Otherwise d = std::move(s);, a self-move when d and s are the same slot. | events |
Tests 6–10 cover this part.
6 make a move 1 get a emplace a copy 2 make b emplace b 3 reset a
ctor 1 move 1 dtor 0 get a 1 ctor 2 dtor 1 copy 2 dtor 2 ctor 3 dtor 2 end dtor 3
make a move 1 constructs a temporary Tracked (ctor 1), move-constructs it into a's storage (move 1), and destroys the moved-from temporary (dtor 0).
emplace a copy 2 builds the local t (ctor 2), destroys a's old value (dtor 1), copy-constructs t into the same bytes (copy 2), and then t goes out of scope (dtor 2).
emplace b 3 constructs object 3 directly in b's storage from the int, with no temporary. reset a destroys the copy of object 2 that a held.
At the end b goes out of scope first and prints dtor 3; a is empty, so its destructor prints nothing.