Home > Software design >  How references can bind to prvalues?
How references can bind to prvalues?

Time:02-15

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?

CodePudding user response:

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.

  • Related