C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Way to get rid of valueless_by_exception in std::variant

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Tue, 28 Oct 2025 11:57:49 +0000
On Tue, 28 Oct 2025 at 11:46, Nikl Kelbon via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> No one really has correct code with std::varant right now, because no one
> handles valueless_by_exception, but its possible to get rid of it.
>
> 0. backup memory of old value
> 1. construct new value ON TOP of memory of old value
> On exception just memswap backup and new value (new value not constructed)
>

That's only valid if the type is trivially copyable, otherwise it's
undefined behaviour.


>
> On success
> 2. memswap 2 buffers - with new value and backup
>

Again, this is potentially undefined behaviour.


> 3. call destructor for old value
> 4. replace buffer without value with new value
>


If your variant alternatives are trivially copyable, then the
implementation should already avoid becoming valueless (IIRC it only
requires nothrow move assignable, not trivially copyable). If the variant
alternatives are not trivially copyable, doing it via memswaps on raw
buffers isn't valid.

Received on 2025-10-28 11:58:05