Boost logo

Boost :

Subject: Re: [boost] Boost.Outcome review - First questions
From: d25fe0be_at_[hidden]
Date: 2017-05-22 19:58:59


> On 23 May 2017, at 03:12, Niall Douglas via Boost <boost_at_[hidden]> wrote:
>
>>> The fact optional implemented .value_or() with a return by value is a
>>> mistake. Expected need not repeat that mistake.
>>
>> I might have missed something, but if .value_or() returns a reference, won't:
>>
>> auto &&s = std::optional<std::string>{}.value_or("temporary"s);
>> std::cout << s << std::endl;
>>
>> triggers undefined behavior?
>>
>> '"temporary"s' is destroyed right after the declaration of 's', hence 's' is
>> a dangling reference.
>>
>> By requiring .value_or() to return by value, this should just work.
>
> Does not the bind to a reference keep the std::string temporary object
> alive?

Yeah it does, as long as .value_or() returns by value.

But if .value_or() returns by reference, the temporary is bound to reference
twice.

The first time is when it's bound to .value_or()'s argument, and the second
time is when it's bound to 's'.

Since the lifetime of temporaries will only be extended once, the second time
it's bound, it's destroyed.

This should demonstrate the UB: https://wandbox.org/permlink/i15zM62PF2WkTM1e

>
> https://godbolt.org/g/ZcLpe5 suggests that it does.

Since std::optional<T>.value_or() returns by value. :)

>
> But you might be onto something. Some other combination with value_or()
> might well produce a reference to a deleted temporary. That would
> explain the choice of value returning semantics for value_or().
>
> Niall
>
> --
> ned Productions Limited Consulting
> http://www.nedproductions.biz/ http://ie.linkedin.com/in/nialldouglas/
>
>
> _______________________________________________
> Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk