C++ Logo

std-proposals

Advanced search

Re: [std-proposals] void std::optional<T>::abandon(void) noexcept

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Tue, 28 Nov 2023 13:33:32 +0000
On Tue, 28 Nov 2023 at 13:09, Frederick Virchanza Gotham <
cauldwell.thomas_at_[hidden]> wrote:

> On Tue, Nov 28, 2023 at 12:34 PM Jonathan Wakely wrote:
> >
> > You can just move the contained value to another object which you don't
> destroy. This doesn't need to be added to std::optional.
>
>
> Your edict is discriminatory against enthusiasts of unmovable
> user-defined classes:
>
> #include <mutex>
> #include <optional>
>
> std::mutex dummy1;
>
> alignas(std::mutex) char unsigned dummy2[sizeof(std::mutex)];
>
> int main(void)
> {
> std::optional< std::mutex > var;
>
> var.emplace();
>
> dummy1 = std::move( var.value() ); // doesn't
> work
> ::new(dummy2) std::mutex( std::move(var.value()) ); // doesn't
> work
> }
>

So just construct a new object over the old one, e.g.

std::construct_at(&var);

This abandons the old one and creates a new empty optional over it.

There's no need to add a new member function for this niche use case.

Received on 2023-11-28 13:33:47