3

I've read tons of pages explaining how const rvalues are used for forbidding use of certain functions, but there was nothing about use case of method like this:

class optional
{
    ...
    constexpr const T&& value() const &&;
    ...
};

Can you name some examples? I am not iterested in examples from other classes. I want to know why commitee decided to include such method in this particular class. What can one do with const rvalue reference coming from optional?

Kasata Ata
  • 365
  • 3
  • 11
  • 1
    If optional is const (the second const makes a hint), the encapsulated value is const, non const rvalue reference can't be returned. – 273K Apr 27 '21 at 20:00
  • This part is easy. But what can one do with const rvalue reference? – Kasata Ata Apr 27 '21 at 20:08
  • @KasataAta copy it; use it's const member functions etc. Same are you can with any `const T &&` – Richard Critten Apr 27 '21 at 20:11
  • What makes returning const rvalue reference better than returning const lvalue reference or just returning by value? – Kasata Ata Apr 27 '21 at 20:13
  • `optional` has to be a const rvalue for this overload to be selected; given you started with a const ravlue this makes sense. You can't (shouldn't) return an lvalue reference to a temporary and the caller can make a copy (of the value) if they need one. Making a copy should not be forced on the caller if they only want a reference. – Richard Critten Apr 27 '21 at 20:16
  • I get the part about persistence of value type. But what about "Making a copy should not be forced on the caller if they only want a reference."? Returning const rvalue reference is forcing copying in the same way as returning value, isn't it? – Kasata Ata Apr 27 '21 at 20:23
  • @KasataAta No, a (rvalue-)reference-to-const can bind to the object referenced by an rvalue-reference-to-const. For example, this makes no copies: `auto& val = std::move(my_const_optional).value(); val.const_member_function();` – Miles Budnek Apr 27 '21 at 20:48

0 Answers0