Topic: [N4529] [optional.object.observe] Is it ok to return


Author: Kazutoshi Satoda <k_satoda@f2.dion.ne.jp>
Date: Sun, 07 Jun 2015 04:16:47 +0900
Raw View
Rvalue overloads of observer member functions of
std::experimental::optional are specified to return rvalue reference
into possibly temporary *this.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4529.html#optional.object.observe
> constexpr T&& value() &&;
> constexpr const T&& value() const &&;
>
> Effects:
>     Equivalent to return bool(*this) ? std::move(*val) : throw bad_optional_access();

That may cause dangling references as shown bellow:

  #include <experimental/optional>
  #include <vector>
  #include <iostream>
  using namespace std;
  using namespace experimental;
  int main() {
    const auto& x = make_optional(vector<int>(1024*1024)).value();
    cout << x.back() << endl; // Segmentation fault
  }

  http://melpon.org/wandbox/permlink/OBibRsBWI4ZdUoyi

The same issue apply to operator*().

Is it ok to have such risk in standard library interface?
(Shouldn't it return a moved value to be safer?)

I found that these overloads were added by N3982.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3982.html
But there seems to be no discussion about this.


FYI, I'm considering to propose a change of any_cast to reduce
unnecessary copy, and looked for what other components do, and came to
the optional case. This is the same issue with boost::any_cast which
added rvalue overload and has been fixed to return value instead of
rvalue reference as it caused a regression.
https://svn.boost.org/trac/boost/ticket/9462

I think it might be a good library-wide guideline not to return rvalue
reference except by move-related utilities like std::move().
https://stackoverflow.com/questions/5770253/is-there-any-case-where-a-return-of-a-rvalue-reference-is-useful

--
k_satoda

--

---
You received this message because you are subscribed to the Google Groups "ISO C++ Standard - Future Proposals" group.
To unsubscribe from this group and stop receiving emails from it, send an email to std-proposals+unsubscribe@isocpp.org.
To post to this group, send email to std-proposals@isocpp.org.
Visit this group at http://groups.google.com/a/isocpp.org/group/std-proposals/.

.