C++26: Std:Optional
21 hours ago
- #C++26
- #Programming
- #C++
- std::optional<T&> is introduced in C++26 to represent optional references, filling a gap left by C++17's std::optional<T>.
- Unlike std::optional<T>, std::optional<T&> is non-owning and behaves like a pointer to T, which may be nullptr.
- Assignments to std::optional<T&> rebind the reference rather than copying the object, ensuring consistent and safe behavior.
- make_optional() does not support optional references to avoid dangling references; construct std::optional<T&> directly instead.
- const std::optional<T&> provides shallow constness; use std::optional<const T&> for deep constness.
- value_or() for std::optional<T&> returns T by value to avoid surprising reference semantics.
- std::optional<T&> reduces reliance on raw pointers and reference wrappers, making code safer and more expressive.