Title
Improve optional<T&>::or_else
Status
new
Section
[optional.ref.monadic]
Submitter
Hewill Kang

Created on 2025-09-07.00:00:00 last changed 4 weeks ago

Messages

Date: 2025-09-15.13:54:44

Proposed resolution:

This wording is relative to N5014.

  1. Modify [optional.ref.monadic] as indicated:

    template<class F> constexpr optional or_else(F&& f) const;
    

    -7- Constraints: `F` models `invocable`.

    -8- Mandates: is_same_v<remove_cvref_t<invoke_result_t<F>>, optional> is `true`.

    -9- Effects: Equivalent to:

    if (has_value()) {
      return *thisval;
    } else {
      return std::forward<F>(f)();
    }
    
Date: 2025-09-07.00:00:00

optional<T&>::or_else currently returns *val when it has a value, which calls the optional(U&&) constructor which in turn calls convert-ref-init-val which in turn calls `addressof`.

There's no reason to do that. It's much more efficient to call optional<T&>'s default copy constructor to just copy a pointer.

History
Date User Action Args
2025-09-15 13:54:44adminsetmessages: + msg15051
2025-09-07 00:00:00admincreate