C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Hope that std::optional and comma expressions can work this way

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Wed, 21 May 2025 16:29:33 +0100
On Wed, May 21, 2025 at 11:36 AM Jonathan Wakely wrote:
>
> > typedef std::optional<int> T;
> > alignas(T) char unsigned storage[sizeof(T)];
> > T &r = *static_cast<T*>(static_cast<void*>(&storage));
> > if ( AllInUniversal() ) std::construct_at(&r, 42 );
> > /****************/ else std::construct_at(&r, std::nullopt);
>
> wat
>
> Why would you want it to be turned into that, rather than what you wrote above?
>
> std::optional<int> r = cond ? std::optional<int>(42) :
> std::optional<int>(std::nullopt);
>
> This already avoids any copy due to guaranteed elision. Your version
> using a byte array and construct_at is just unnecessarily complex.



Obviously my code is pretty horrible -- I was trying to give an idea
of what would happen "under the hood", so to speak. I was trying to
show how the ternary operator might, under the hood, be turned into an
"if - else" resulting in two separate statements to initialise the
"optional" variable.

Received on 2025-05-21 15:29:45