Course outline

C++ / Intermediate / Lesson 14

Optional values and explicit absence

Represent expected absence with C++ optional values and explicit fallbacks.

About 20 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Distinguish absence from a present zero.
  • Choose and test an explicit fallback policy.
  • Design a contract that distinguishes expected absence from domain values and separately meaningful failures.
  • Safely access, replace, and compose optional values while accounting for ownership and fallback evaluation.

Model expected absence

Some operations can succeed without producing a value, such as looking up an optional setting. std::optional represents either a value or absence without reserving an ordinary value as a sentinel. Decide whether absence is expected or an error before selecting the return type. A missing value does not automatically explain why it is missing; preserve a separate error representation when callers need that distinction.

Check before access

An optional can be tested before its contained value is accessed. The example returns zero for a valid key and absence for another key; zero remains a real value rather than being confused with missing data. Dereferencing a disengaged optional is invalid, so keep the check and use close together. The returned optional owns its contained integer and does not depend on a local integer remaining alive.

cpp Optional value example
#include <iostream>
#include <optional>
#include <string_view>

std::optional<int> find_count(std::string_view key) {
    if (key == "empty") return 0;
    return std::nullopt;
}

int main() {
    auto count = find_count("empty");
    if (count) std::cout << *count << "\n";
}
Expected output
0

A present zero passes the optional check and is printed.

Choose fallback policy

value_or selects a fallback when an optional is empty. Choose that fallback from the domain contract, not merely because a default makes the program continue. The example deliberately distinguishes an empty optional from one containing zero. If the computation of a fallback has side effects or is expensive, account for ordinary function-argument evaluation and use an explicit conditional when lazy evaluation is needed.

cpp Optional value example
#include <iostream>
#include <optional>

int main() {
    std::optional<int> missing;
    std::optional<int> zero = 0;
    std::cout << missing.value_or(5) << " " << zero.value_or(5) << "\n";
}
Expected output
5 0

The fallback applies only to the empty optional.

Own the contained value

When an optional contains a class, its own lifetime and the contained object’s lifetime are linked. References or pointers to the contained object become invalid when it is destroyed or replaced. Avoid returning such observers beyond the optional’s lifetime. Pass an optional by value or reference according to the ownership and cost contract, and remember that copying a wrapper can still copy objects that themselves share resources.

Test distinct outcomes

Test three distinct cases: absence, a present ordinary value, and a present boundary value such as zero. If errors are separate from absence, test their paths independently. Confirm that a caller never dereferences an empty optional and that a fallback is used only where the contract allows it. A test that exercises only a present nonzero value cannot distinguish absence from a sentinel-based design.

Meaning of absence

An optional carries two states: disengaged, or engaged with a value of its element type. This makes a missing setting different from a valid setting whose integer happens to be zero. The wrapper does not say why a value is missing, and it should not silently replace information the caller needs. A search that finds no matching item can reasonably return an empty optional; a network operation with timeout, authorization failure and malformed data needs an additional error model if callers must react differently.

Write the contract before implementing a lookup: identify when absence is normal, what a present value means, and whether the returned object owns its data. A sentinel can collide with valid inputs or require every caller to remember a special convention. Optional makes engagement explicit, but a caller can still choose an inappropriate fallback or ignore a separate error, so type choice is only part of the design.

Engagement and safe access

A default constructed optional is empty; constructing it with a value, assigning a value, or emplacing an object engages it. Test engagement with has_value or its contextual Boolean conversion before dereferencing. An engaged optional containing false, zero, or an empty string still passes that test: engagement concerns the wrapper, not the truth or size of the contained object. Keep the check near the access and reconsider it after any operation that can reset or replace the value.

Dereferencing an empty optional violates its precondition. The checked value() member throws std::bad_optional_access when empty, which can be useful at a boundary where absence is exceptional, but checking explicitly is clearer when absence is expected. Do not rely on a particular observed result of invalid dereference. A reference obtained from an optional becomes invalid when the contained object is destroyed, including reset or replacement; do not retain it across those operations.

Fallback and evaluation

value_or returns a value when engaged and a supplied fallback otherwise. A fallback should express a documented policy: a missing page size might use a configured default, while a missing account balance may require the caller to stop. The fallback cannot distinguish different causes that an optional has already collapsed. Test both a present boundary value and the empty path so a valid zero is not accidentally replaced.

Function arguments are evaluated before a call, so an expensive or side-effecting fallback expression is evaluated even when value_or ultimately returns the contained value. Use a conditional or an explicit branch if fallback work must be lazy. The result of value_or is a value rather than a persistent alias to the contained object; consider copying cost and ownership when the element type is large or move-only.

Ownership and composition

An optional owns its contained T, but ownership of resources reachable through T depends on T. An optional string owns its string contents, whereas an optional string_view still observes characters owned elsewhere. Returning a view into a local string leaves a dangling view even if the optional itself is returned by value. Prefer an owning string when the returned data must outlive its source, or document and enforce the source lifetime.

Pass an optional by const reference for read-only access to an existing wrapper when its lifetime covers the call; return by value when returning an independently owned result. Reset destroys the contained object, and emplace destroys an existing value before constructing the replacement. If construction fails, consider the operation’s documented guarantees rather than assuming the old object remains. Avoid holding pointers or references to the old object through replacement.

Testing and boundaries

Exercise three independent observations: an absent result, a normal present value, and a present boundary value such as zero or false. Add tests for any documented separate error outcomes and for the caller’s fallback policy. A test that checks only nonzero values cannot establish that absence differs from zero; a test that merely verifies a fallback cannot prove that present values are preserved.

When chaining lookups, check each optional before using its contents and specify whether a missing intermediate item should stop the operation or trigger a fallback. Log or return diagnostic information separately when it is meaningful to the caller, without claiming that an empty optional alone identifies a cause. The examples below were compiled and run locally in C++17 mode and use facilities available in the course’s C++20 baseline; their results describe only their synthetic inputs.

20 worked examples

1. Present false

Problem: Show that a present false value still engages the wrapper.

  1. The optional contains the Boolean value false.
  2. The engagement test succeeds even though the contained Boolean is false.
cpp Present false
#include <optional>
#include <iostream>
int main(){std::optional<bool> flag=false; std::cout<<flag.has_value()<<" "<<*flag;}
Expected output
1 0

Why this result follows: The optional contains the Boolean value false. The engagement test succeeds even though the contained Boolean is false.

2. Absent lookup

Problem: Handle a missing key without dereferencing an empty result.

  1. The lookup recognizes only the key alpha.
  2. The requested beta is absent, so the caller reports missing.
cpp Absent lookup
#include <optional>
#include <iostream>
#include <string_view>
std::optional<int> find(std::string_view key){if(key=="alpha") return 4; return std::nullopt;}
int main(){auto x=find("beta"); if(x) std::cout<<*x; else std::cout<<"missing";}
Expected output
missing

Why this result follows: The lookup recognizes only the key alpha. The requested beta is absent, so the caller reports missing.

3. Checked access

Problem: Observe the documented exception when value() is called on an empty wrapper.

  1. The default constructed optional starts disengaged and has no contained integer.
  2. value() throws bad_optional_access, which the handler catches.
cpp Checked access
#include <optional>
#include <iostream>
int main(){std::optional<int> x; try{(void)x.value();}catch(const std::bad_optional_access&){std::cout<<"caught";}}
Expected output
caught

Why this result follows: The optional starts disengaged. value() throws bad_optional_access, which the handler catches.

4. Reset an object

Problem: Observe engagement after explicitly clearing an optional string.

  1. The wrapper initially contains an owning string.
  2. reset destroys that value and makes the wrapper empty.
cpp Reset an object
#include <optional>
#include <string>
#include <iostream>
int main(){std::optional<std::string> name="Ada"; name.reset(); std::cout<<name.has_value();}
Expected output
0

Why this result follows: The wrapper initially contains an owning string. reset destroys that value and makes the wrapper empty.

5. Emplace a string

Problem: Construct a string in an empty optional with a count and character.

  1. The wrapper starts empty.
  2. emplace constructs three x characters in its contained string.
cpp Emplace a string
#include <optional>
#include <string>
#include <iostream>
int main(){std::optional<std::string> s; s.emplace(3,'x'); std::cout<<*s;}
Expected output
xxx

Why this result follows: The wrapper starts empty. emplace constructs three x characters in its contained string.

6. Lazy fallback

Problem: Avoid evaluating a fallback function when a value is already present.

  1. The optional contains nine, so the conditional selects its first branch.
  2. The fallback function is not called and the call counter remains zero.
cpp Lazy fallback
#include <optional>
#include <iostream>
int fallback(int& calls){++calls; return 7;}
int main(){std::optional<int> x=9; int calls=0; int n=x?*x:fallback(calls); std::cout<<n<<" "<<calls;}
Expected output
9 0

Why this result follows: The optional contains nine, so the conditional selects its first branch. The fallback function is not called and the call counter remains zero.

7. Eager value_or argument

Problem: Observe evaluation of a fallback even for a present value.

  1. The fallback expression is an argument evaluated before value_or runs.
  2. The returned value remains nine while the counter increments.
cpp Eager value_or argument
#include <optional>
#include <iostream>
int fallback(int& calls){++calls; return 7;}
int main(){std::optional<int> x=9; int calls=0; int n=x.value_or(fallback(calls)); std::cout<<n<<" "<<calls;}
Expected output
9 1

Why this result follows: The fallback expression is an argument evaluated before value_or runs. The returned value remains nine while the counter increments.

8. Own returned text

Problem: Return a substring that remains valid after the source function returns.

  1. The function constructs an owning string in the optional.
  2. The caller can safely print that owned text after the local source is destroyed.
cpp Own returned text
#include <optional>
#include <string>
#include <iostream>
std::optional<std::string> prefix(){std::string local="apple"; return local.substr(0,3);}
int main(){auto s=prefix(); if(s) std::cout<<*s;}
Expected output
app

Why this result follows: The function constructs an owning string in the optional. The caller can safely print that owned text after the local source is destroyed.

9. Empty string is present

Problem: Distinguish an empty string from an absent string.

  1. The wrapper is engaged with a string of length zero.
  2. Its engagement and its content length answer different questions.
cpp Empty string is present
#include <optional>
#include <string>
#include <iostream>
int main(){std::optional<std::string> s=std::string{}; std::cout<<s.has_value()<<" "<<s->size();}
Expected output
1 0

Why this result follows: The wrapper is engaged with a string of length zero. Its engagement and its content length answer different questions.

10. Copy independence

Problem: Copy an optional integer and modify only the copy.

  1. Copying an engaged optional copies its integer value.
  2. Changing the second wrapper does not modify the first integer.
cpp Copy independence
#include <optional>
#include <iostream>
int main(){std::optional<int> a=3; auto b=a; *b=8; std::cout<<*a<<" "<<*b;}
Expected output
3 8

Why this result follows: Copying an engaged optional copies its integer value. Changing the second wrapper does not modify the first integer.

11. Move-only ownership

Problem: Transfer a unique pointer held inside an optional.

  1. The contained unique_ptr is moved to a separate owner.
  2. The destination owns the integer; the optional remains engaged with a null moved-from pointer.
cpp Move-only ownership
#include <optional>
#include <memory>
#include <iostream>
int main(){std::optional<std::unique_ptr<int>> x{std::make_unique<int>(6)}; auto p=std::move(*x); std::cout<<*p<<" "<<x.has_value()<<" "<<bool(*x);}
Expected output
6 1 0

Why this result follows: The contained unique_ptr is moved to a separate owner. The destination owns the integer; the optional remains engaged with a null moved-from pointer.

12. Search index

Problem: Return an optional index instead of a sentinel for an absent element.

  1. The linear search returns the first matching index.
  2. The caller checks engagement before using the index to read the vector.
cpp Search index
#include <optional>
#include <vector>
#include <iostream>
std::optional<std::size_t> find(const std::vector<int>& v,int target){for(std::size_t i=0;i<v.size();++i) if(v[i]==target) return i; return std::nullopt;}
int main(){std::vector<int> v{4,7,4}; auto i=find(v,4); if(i) std::cout<<*i<<":"<<v[*i];}
Expected output
0:4

Why this result follows: The linear search returns the first matching index. The caller checks engagement before using the index to read the vector.

13. Separate error state

Problem: Keep a parse failure distinct from a missing optional setting.

  1. A separate status identifies malformed input in this small result type.
  2. The absent value alone does not identify that status.
cpp Separate error state
#include <optional>
#include <iostream>
enum class Status{ok,missing,invalid}; struct Result{Status status; std::optional<int> value;};
int main(){Result r{Status::invalid,std::nullopt}; std::cout<<(r.status==Status::invalid)<<" "<<r.value.has_value();}
Expected output
1 0

Why this result follows: A separate status identifies malformed input in this small result type. The absent value alone does not identify that status.

14. Chain two lookups

Problem: Stop when an intermediate lookup has no value.

  1. The first lookup returns an identifier for the known name.
  2. The second lookup has no record for that identifier, so the final result is empty.
cpp Chain two lookups
#include <optional>
#include <iostream>
#include <string_view>
std::optional<int> id(std::string_view n){if(n=="Ada") return 2; return std::nullopt;}
std::optional<int> score(int i){if(i==1) return 90; return std::nullopt;}
int main(){auto i=id("Ada"); auto s=i?score(*i):std::nullopt; std::cout<<(s?"found":"missing");}
Expected output
missing

Why this result follows: The first lookup returns an identifier for the known name. The second lookup has no record for that identifier, so the final result is empty.

15. Compare absence

Problem: Compare optional values without treating zero as missing.

  1. An empty optional is unequal to an engaged optional holding zero.
  2. Equality distinguishes their engagement states before comparing contained values.
cpp Compare absence
#include <optional>
#include <iostream>
int main(){std::optional<int> a,b=0; std::cout<<(a==b)<<" "<<(b==0);}
Expected output
0 1

Why this result follows: An empty optional is unequal to an engaged optional holding zero. Equality distinguishes their engagement states before comparing contained values.

16. Assign a value

Problem: Engage an initially empty optional by assigning a value.

  1. The default constructed wrapper is disengaged.
  2. Assignment constructs its integer value and engages it.
cpp Assign a value
#include <optional>
#include <iostream>
int main(){std::optional<int> x; std::cout<<x.has_value()<<" "; x=12; std::cout<<x.has_value()<<" "<<*x;}
Expected output
0 1 12

Why this result follows: The default constructed wrapper is disengaged. Assignment constructs its integer value and engages it.

17. Optional parameter

Problem: Apply a caller-specified limit only when one is supplied.

  1. The empty limit means no cap in this function contract.
  2. An engaged limit of three caps a count of eight at three.
cpp Optional parameter
#include <optional>
#include <algorithm>
#include <iostream>
int cap(int count,std::optional<int> limit){return limit?std::min(count,*limit):count;}
int main(){std::cout<<cap(8,std::nullopt)<<" "<<cap(8,3);}
Expected output
8 3

Why this result follows: The empty limit means no cap in this function contract. An engaged limit of three caps a count of eight at three.

18. Reference wrapper

Problem: Mutate an existing object through an explicitly optional reference wrapper.

  1. reference_wrapper stores a reference to the existing integer.
  2. Changing its get() result changes the original integer.
cpp Reference wrapper
#include <optional>
#include <functional>
#include <iostream>
int main(){int n=2; std::optional<std::reference_wrapper<int>> ref=std::ref(n); if(ref) ref->get()=5; std::cout<<n;}
Expected output
5

Why this result follows: reference_wrapper stores a reference to the existing integer. Changing its get() result changes the original integer.

19. Swap states

Problem: Exchange an engaged optional and an empty one.

  1. The first wrapper contains a string and the second is empty.
  2. After swap the first is empty and the second owns the string.
cpp Swap states
#include <optional>
#include <string>
#include <iostream>
int main(){std::optional<std::string> a="tea",b; a.swap(b); std::cout<<a.has_value()<<" "<<*b;}
Expected output
0 tea

Why this result follows: The first wrapper contains a string and the second is empty. After swap the first is empty and the second owns the string.

20. Parse without sentinel

Problem: Return absence for a non-digit while accepting zero as a digit.

  1. The character zero maps to the integer value zero.
  2. The letter is rejected, so its optional is disengaged.
cpp Parse without sentinel
#include <optional>
#include <iostream>
std::optional<int> digit(char c){if(c<'0'||c>'9') return std::nullopt; return c-'0';}
int main(){auto a=digit('0'),b=digit('x'); std::cout<<*a<<" "<<b.has_value();}
Expected output
0 0

Why this result follows: The character zero maps to the integer value zero. The letter is rejected, so its optional is disengaged.

Common errors and fixes

An empty optional is dereferenced

Why it happens
The presence check was omitted.
How to fix it
Check engagement before access.
Prevent it next time
Test the absence path.

Zero is treated as absence

Why it happens
A sentinel and a valid value were conflated.
How to fix it
Represent absence with an empty optional.
Prevent it next time
Test a present zero.

A fallback hides an error

Why it happens
Absence and failure share an unclear contract.
How to fix it
Represent the failure separately when required.
Prevent it next time
Document each outcome.

20 practice exercises

1. What does value_or(5) return for an optional containing zero?

Show hint

Check whether the wrapper contains a value, not whether its value is truthy.

Show worked solution

It returns zero because the optional is engaged. The fallback is used only when no value is present.

An optional containing zero is engaged. value_or therefore returns the contained zero; five would be used only if the wrapper were disengaged.

Check your solution

  • The present zero produces 0.
  • An empty optional produces the fallback 5.

2. Why might optional be insufficient for a failed network request?

Show hint

List failure reasons the caller may need to distinguish.

Show worked solution

Absence alone does not identify the failure. If the caller must distinguish timeout from invalid data, return an explicit error representation too.

An empty optional communicates only absence, so timeout and invalid data would be indistinguishable. Return a separate status or an error-bearing result when the caller needs different recovery actions, and document how success relates to the value.

Check your solution

  • Timeout and invalid data can be distinguished.
  • A successful response carries its value.

3. A configuration lookup returns optional<int>. Its documented default is 30 seconds; a stored value of zero disables the timeout. Describe the caller behavior for missing and zero.

Show hint

Distinguish engagement from the contained integer.

Show worked solution

Use the documented default only when the optional is empty. A present zero is an explicit request to disable the timeout and must remain zero; test both paths and a positive configured value.

Check your solution

  • Missing selects 30 seconds.
  • Present zero remains zero and disables the timeout.

4. A function returns optional<string_view> into a local string. Explain the lifetime defect and give an owning alternative.

Show hint

The wrapper does not own characters observed by a view.

Show worked solution

The local string is destroyed on return, leaving the view dangling even though the optional itself survives. Return optional<string> with an owned copy, or ensure and document that the observed storage outlives every use of the view.

Check your solution

  • The returned value does not refer to destroyed local storage.
  • The ownership and lifetime contract is explicit.

5. An optional<int> holds -1. A caller writes if (*value) before checking engagement. Identify two independent problems and a safe decision sequence.

Show hint

Check the wrapper before the contained value.

Show worked solution

Dereferencing an empty wrapper violates its precondition, and a truth test does not establish that a number is valid for the domain. First test value, then validate the contained integer against the stated range, including whether -1 is allowed.

Check your solution

  • No empty optional is dereferenced.
  • Domain validity is checked independently of engagement.

6. A cache lookup returns empty for a missing key and also for a storage failure. The caller must retry failures but not misses. Propose an interface.

Show hint

The caller needs more than one kind of non-value.

Show worked solution

Use a result type that explicitly distinguishes found value, missing key and storage error, for example a status enum paired with an optional value and a defined invariant. Test all three outcomes and ensure an error cannot be mistaken for an ordinary miss.

Check your solution

  • Missing and storage error are distinct outcomes.
  • A found result carries the expected value.

7. A program uses setting.value_or(load_default()) and load_default increments a metric. The setting is present. Predict the metric and propose lazy behavior.

Show hint

Ordinary function arguments are evaluated before the call.

Show worked solution

load_default is evaluated even when setting is present, so the metric increments. Use an explicit conditional such as setting ? *setting : load_default() to call it only when the setting is empty; test the counter in both branches.

Check your solution

  • The present branch does not call the lazy fallback.
  • The empty branch calls the fallback once.

8. An optional vector contains an empty vector. A review labels it missing because size is zero. Explain the distinction and give two tests.

Show hint

Engagement and container size describe different properties.

Show worked solution

An engaged optional can contain an empty vector, meaning a value exists with no elements. Test an empty optional separately from an engaged empty vector and assert both engagement and size according to the application contract.

Check your solution

  • The absent wrapper has no value.
  • The present empty vector is engaged and has size zero.

9. A function obtains a reference to *name and then calls name.reset(). Explain whether the reference may be used afterward.

Show hint

Reset destroys the contained object.

Show worked solution

Reset destroys the string inside the optional, so the reference becomes invalid and must not be accessed afterward. Finish using the reference before reset, or copy the needed text into an independent owning string first.

Check your solution

  • No reference to the destroyed value is used.
  • An independent copy remains usable after reset.

10. An optional<int> contains 6 and is copied. The copy is reset. State the original state and explain why.

Show hint

The integer belongs to each wrapper separately.

Show worked solution

Copying the engaged optional creates a separate contained integer in the copy. Resetting the copy destroys only that integer; the original remains engaged with 6. This independence does not imply that every contained type owns all of its reachable resources.

Check your solution

  • The original is engaged and equals 6.
  • The copy is empty after reset.

11. A parser accepts the text "off" and numeric ports 1 through 65535. Explain why one optional<int> may be insufficient if invalid text must be reported separately.

Show hint

Both an intentional absence and a parse error are possible.

Show worked solution

An empty optional alone cannot distinguish an intentionally disabled setting from invalid text. Return a result with separate disabled, valid port and invalid outcomes, or combine a status with an optional value under a documented invariant.

Check your solution

  • The input "off" produces the disabled outcome.
  • Invalid text produces an error distinct from disabled.

12. A lookup returns an optional index into a vector. The vector is then erased or reordered before the index is used. Explain the risk and a safer contract.

Show hint

An index is a value but its meaning depends on the collection.

Show worked solution

The stored index may now name a different element or fall outside the vector after modification. Use it before structural changes, return an independent value or stable identifier, or enforce a collection lifetime and mutation contract; test the chosen policy.

Check your solution

  • The consumer does not assume the old index still identifies the same element.
  • The contract specifies how collection changes are handled.

13. An optional<string> contains "red". A caller invokes emplace to replace it with a new string and retains an old reference. Explain the lifetime and exception concern.

Show hint

Replacement destroys the old contained object.

Show worked solution

emplace destroys the old string before constructing the new one, invalidating references to the old object. If construction throws, do not assume the original remains; prepare a separate value first and choose a commit strategy appropriate to the required guarantee.

Check your solution

  • No old reference is used after replacement.
  • Failure behavior is specified and tested for the chosen strategy.

14. A function uses value() on an empty optional. Name the exception and explain when explicit checking is preferable.

Show hint

value() has a checked failure path.

Show worked solution

value() throws std::bad_optional_access for an empty wrapper. If absence is an expected outcome, check engagement and handle that branch explicitly; reserve exception handling for a contract where missing data is truly exceptional.

Check your solution

  • The empty call is recognized as throwing bad_optional_access.
  • The normal absence branch is handled without an unchecked dereference.

15. A caller compares optional<bool>{false} with an empty optional. Explain their difference and write two observations to test.

Show hint

A false value is still a value.

Show worked solution

The false wrapper is engaged and contains false; the empty wrapper is disengaged. Check has_value for each and inspect the Boolean only after confirming engagement, so false is not interpreted as missing.

Check your solution

  • The false wrapper has a value equal to false.
  • The empty wrapper has no value.

16. A batch lookup returns optional<Record> for each key. Design a loop policy that collects missing keys while retaining found records.

Show hint

Handle each result before accessing it.

Show worked solution

For each key, check the returned optional; append the owned record to the found collection when present and append the key to a separate missing collection otherwise. Test a batch with both outcomes and preserve input association where ordering matters.

Check your solution

  • Found records are collected without dereferencing missing results.
  • Missing keys are reported separately and retain their identity.

17. A function accepts optional<int> limit. Decide and document a policy for an absent limit and for a present negative limit.

Show hint

Absence and invalid input need explicit separate rules.

Show worked solution

One valid policy is no cap when absent and rejection when the present limit is negative. Check engagement before validating the number, then test absence, zero, a positive limit and a negative limit; document the policy for callers.

Check your solution

  • Absence follows the documented no-cap policy.
  • A present negative limit is rejected rather than treated as absent.

18. An optional<unique_ptr<Item>> is moved out through std::move(*holder). Explain both the wrapper state and pointer state afterward.

Show hint

Moving the contained pointer is different from resetting the wrapper.

Show worked solution

The optional remains engaged, while the moved-from unique_ptr no longer owns the item and is null. The destination owns the item; check both wrapper engagement and contained pointer before dereferencing, or reset the wrapper deliberately.

Check your solution

  • The destination owns the original item.
  • The wrapper remains engaged but its contained pointer is null.

19. A caller wants a default string but cannot afford a copy of a large present string. Explain why value_or may be unsuitable and propose a lifetime-aware alternative.

Show hint

value_or returns a value rather than a persistent reference.

Show worked solution

value_or produces a value and can require copying from an lvalue optional. If the consumer only reads during the wrapper lifetime, branch and pass a const reference to either the contained string or a sufficiently long-lived fallback; do not return a reference to a temporary fallback.

Check your solution

  • The referenced string outlives its use.
  • The design avoids an unnecessary copy for the present case.

20. Design tests for a digit parser returning optional<int>, accepting ASCII digit characters and rejecting other input.

Show hint

Include a valid boundary and an invalid character.

Show worked solution

Test characters 0 and 9 for engaged results containing zero and nine, and a non-digit such as x for absence. Assert engagement before accessing each value and keep the character encoding assumptions in the parser contract.

Check your solution

  • Both boundary digits are present with their numeric values.
  • The non-digit result is empty.

Key takeaways

  • An optional models a value or expected absence.
  • Check engagement and preserve required error information.
  • Engagement is independent of whether a contained value is zero, false, or empty.
  • value_or evaluates its fallback argument before the call; branch explicitly for lazy work.
  • An optional owns its contained object, but a view or reference inside it may still depend on external lifetime.

Official references