Skip to content
Guest
Learn C++ · Course Syllabus Show lessons
Modern C++20 Features · 8 min read · Intermediate

std::optional & std::string_view

Express nullable return values cleanly with std::optional and read strings with zero allocations using std::string_view.

What you'll learn

  • Return std::optional<T> instead of magic sentinel values like -1 or empty strings
  • Use .value_or() for safe defaults
  • Accept read-only string slices without allocating via std::string_view
  • std::optional<T> represents a value that may or may not be present (std::nullopt), replacing fragile sentinel values like -1.
  • std::string_view is a lightweight non-owning view (pointer + length) over any std::string or string literal with zero heap allocation.

Fill-in-the-Blank Exercise

Safe Optional Default

Return std::nullopt when not found and unwrap with value_or().

std::optional<int> found = std::;
int score = found.(0);

Live Code Lab

C++optional_view.cpp
Expected OutputClick “Run Live” to compile with GCC 13 (C++20)
gold=1 unknown=99

Check Your Understanding

Score: 0 / 1

1. Why is std::string_view fast for read-only string parameters?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind