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

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 one T. Otherwise it is empty.
  • Placement new: ::new (static_cast<void*>(storage_)) T(args) runs a T constructor 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 at p. 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. Tracked is 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. #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.

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 empty Optional<Tracked> must not construct a Tracked, and Tracked has no default constructor at all.
  • alignas(T) gives the array T's alignment, the rule that places struct fields at aligned offsets. Without it, a T built 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 span storage_ is bytes again. The compiler can't track this, so the class does.
  • The class keeps one invariant: engaged_ is true exactly when a live T occupies storage_.

Reaching the value

  • reinterpret_cast<T*>(storage_) has the right type and address, but formally it still points at the byte array, not at the T that placement new created there.
  • std::launder, from <new>, returns a pointer to the object that actually lives at that address. So std::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

MemberContractCalled 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() consttrue when engaged.get s
value(), operator*(), operator->()The held value. Never called on an empty Optional.get s
  • value() and operator* return T&, and operator-> returns T*. Each has a const overload that returns const T& or const T*.
  • Each constructor and each emplace builds exactly one T with one constructor call: no extra copy, no extra move, no temporary.
  • emplace uses two features that the editor already declares:
    • template <class... Args> makes Args a parameter pack, so emplace accepts any number of arguments of any types and hands them all to T'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 for T (using a second driver type whose alignment is 16);
  • the move constructor is noexcept whenever T'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: make names an absent slot, and every other command names present slots.
CommandWhat the driver runsPrints
make sOptional<Tracked> s;nothing
make s copy idTracked t(id); Optional<Tracked> s(t);, then t goes out of scopeevents
make s move idOptional<Tracked> s(Tracked(id));events
emplace s ids.emplace(id);events
emplace s copy idTracked t(id); s.emplace(t);, then t goes out of scopeevents
emplace s move ids.emplace(Tracked(id));events
reset ss.reset();events
get ss.has_value(), then, if engaged, value(), *s, and s-> through both a const and a non-const referenceget s empty or get s id
drop ss goes out of scope: its destructor runs and the slot becomes absent.events
allocsCounts the heap allocations made inside Optional members so far.allocs n

Part 1: Storage, emplace, and reset

  1. Implement the members in the class table.
  2. Keep engaged_ in step with the storage on every path. A value that is never destroyed is missing its dtor line, and a value destroyed twice prints two.
  3. A correct class allocates nothing, so every allocs line prints allocs 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 an int. copy id or move id: copy- or move-constructed. dtor id: destroyed.
  • copyassign old from new or moveassign old from new: copy- or move-assigned. The object that held old now holds new.
  • Moving from a Tracked sets the source's id to 0, so a moved-from value prints as 0. For example, dtor 0 prints when the temporary in make s move id dies.
  • get asks all six accessors for the value. They must return the same address, inside the Optional object's own bytes; otherwise get prints get s mismatch or get s outside instead of the id. A correct class never prints either.
  • allocs counts calls to the global operator new made while an Optional member 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 by copy or move into 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.

MemberContractCalled 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:

*thisotherCopy assignmentMove assignment
emptyemptynothingnothing
emptyengagedcopy-constructs a T from other's value in storage_move-constructs it
engagedemptydestroys its value and becomes emptythe same
engagedengagedT's copy assignmentT's move assignment
  1. Assigning an Optional to itself changes nothing and calls nothing on the Tracked. This rule is an addition to std::optional's.
  2. When both sides are engaged, the existing T is assigned rather than destroyed and rebuilt, so the only event is one copyassign or moveassign line.
  3. A moved-from Optional is not empty. Like std::optional, it keeps its value in the moved-from state, which for Tracked means id 0.

Two commands are new:

CommandWhat the driver runsPrints
copy d sIf d is absent, Optional<Tracked> d(s);. Otherwise d = s;, a self-copy when d and s are the same slot.events
move d sIf 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.

Example
Input
6
make a move 1
get a
emplace a copy 2
make b
emplace b 3
reset a
Output
ctor 1
move 1
dtor 0
get a 1
ctor 2
dtor 1
copy 2
dtor 2
ctor 3
dtor 2
end
dtor 3
Explanation

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.