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 20:55:55 +0000
On Tue, 28 Nov 2023 at 13:33, Jonathan Wakely <cxx_at_[hidden]> wrote:

>
>
> 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.
>
>
Or use std::unique_ptr<std::mutex> instead of std::optional<std::mutex>,
and then use release() to "abandon" it.

There are already several ways to do this niche thing if you really need it.

Received on 2023-11-28 20:56:10