No, the type could also be non-trivial (and certainly non-empty). For example, std::string could opt-in to the protocol. Then std::optional<std::string>::~optional() would unconditionally destroy the carried string.

The cost of constructing the dummy value (a few zero writes) is less than the cost of the conditional to avoid destroying it.

I don't see what std::expected has to do with it.

On Sat, 2025-06-07 at 12:00 +0200, Robin Savonen Söderholm via Std-Proposals wrote:
If I understand correctly, you are essentially talking about the intersection of a type that "is_trivial" and "is_empty" or the very least has a small size. I believe that std::optional could do various optimizations based around those criteria..
I am not sure if this is so useful as to warrant a new construct. You do know that std::expected has a void specialisation if you are just dealing with empty types anyway?

// Robin

On Sat, Jun 7, 2025, 11:33 Avi Kivity via Std-Proposals <std-proposals@lists.isocpp.org> wrote:
Consider std::optional<T>.

The move constructor has to check if the moved-from optional is
engaged, and if so, move-construct the contained T. Similarly other
special functions have to take actions conditionally. The destructor
has to check if the optional is engaged and only invoke T::~T() if
that's the case.

However, if we had a way to cheaply create a T, we could use that and
avoid all the conditionals. Let's say the protocol is


template <typename T>
struct construct_empty {};


template <>
struct construct_empty<my_lovely_type> {
    static void operator()(my_lovely_type* where) noexcept;
};

If construct_empty is specialized for a T, then optional<T>'s default
constructor could initialize the contained T whether or not the
optional is engaged or not, and all the conditionals for the special
methods would disappear. For trivially constructible standard types,
construct_empty would do nothing. For many standard types, we could
call the default constructor. The user could opt-in for cheaply
constructible user types, often just calling the default constructor.

This seems related to trivial relocation, just from the other side as
it were. Maybe opt-in should also be via an attribute.