3

cppreference says that: a temporary object is created when a reference is bound to prvalue. Do they mean const lvalue references and rvalue references?:

Temporary objects are created when a prvalue is materialized so that it can be used as a glvalue, which occurs (since C++17) in the following situations:

  • binding a reference to a prvalue

If they mean that, does rvalue references and const lvalue reference bound to prvalues of same type creates a temporary? I mean, does this is happening:

const int &x = 10; // does this creates temporary?

int &&x2 = 10; // does this creates temporary?

1 Answers1

5

The only references that are allowed to bind to object rvalues (including prvalues) are rvalue references and const non-volatile lvalue references. When such a binding occurs to a prvalue, a temporary object is materialized. Temporary materialization thus occurs in both of the OP's examples:

const int &x = 10;
int &&x2 = 10;

The first temporary (with value 10) will be destroyed when x goes out of scope. The second temporary (also with value 10, although its value can be modified using x2) will be destroyed when x2 goes out of scope.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • Thanks alot. I just need to ask, cppreference says that, temporaries are created when prvalue is materialized and that's occur when [those situations] (https://en.cppreference.com/w/cpp/language/lifetime#Temporary_object_lifetime) are met. And then said that temporary materialization (i.e prvalue materialization i.e prvalue->xvalue) is occur in [those other situations](https://en.cppreference.com/w/cpp/language/implicit_conversion#Temporary_materialization). Now what the "reference" I should revisit? –  Feb 15 '22 at 01:35
  • 4
    @cpper Please post a new question. – Brian Bi Feb 15 '22 at 01:42
  • `x` is bound **indirectly** to the resultant xvalue while `x2` is bound **directly** to the resultant xvalue. Right? – mada Aug 29 '22 at 16:25
  • @John That needs to be posted as a separate question. – Brian Bi Aug 30 '22 at 00:03