GCC Newspaper
JULY 29, 2026
Date
/
Architectures
Components
Topics
News & Policy
libstdc++

libstdc++: Return optional<const _Ex&> from exception_ptr_cast

Updates exception_ptr_cast to return optional<const _Ex&>, implementing P3981R2 and improving exception handling.

This commit implements the latter half of the P3981R2 proposal by changing the return type of std::exception_ptr_cast from a reference to optional<const _Ex&>. This change requires including the <optional> header for several related functions, such as value, transform, and and_then, to avoid cyclic includes and instantiation issues. A new public helper function, _S_from_ptr, is also introduced for optional<T&> to simplify construction from pointers.

In Details

This change completes the P3981R2 work on std::exception_ptr_cast by modifying its return type to std::optional<const _Ex&>. This necessitates including <optional> in libsupc++/exception_ptr.h and potentially other headers for functions like value, transform, and and_then to resolve header dependency issues and avoid cyclic includes. The patch also introduces optional<T&>::_S_from_ptr, a public helper for constructing optional references from raw pointers, addressing a utility gap.

For Context
P3981R2
A C++ standard proposal focused on improving return types for std::inplace_vector and std::exception_ptr_cast, aiming for more robust and expressive error handling.
std::exception_ptr_cast
A function in C++ that attempts to cast an std::exception_ptr to a specific exception type, returning a pointer to the exception if successful.
std::optional
A C++17 wrapper type that may or may not contain a value. It's used to represent optional return values or nullable pointers safely.
cyclic include
A situation in C++ header files where header A includes header B, and header B (directly or indirectly) includes header A, which can lead to compilation errors or unexpected behavior.
libsupc++
The C++ support library used by GCC, containing essential runtime components like exception handling and type information.
Filed Under: libstdc++exception handlingoptionalcpp26