On 23 May 2017, at 03:12, Niall Douglas via Boost
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::optionalstd::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