0

Consider the follwoing code:

int main() 
{
    const int& number=10;
    cout << number << endl << &number << endl;
    return 0;
}

As output I get:

10
0x62ff08

As far as I know "10" is an rvalue without memory adress, so where does the memory adress come from?

tempdev nova
  • 211
  • 1
  • 8

1 Answers1

1

When you wrote:

//------------------vv---->10 is a prvalue and temporary materialization will result in an xvalue
const int& number = 10;

temporary materialization happens as can be seen from temporary materilization:

Temporary materialization occurs in the following situations:

  • when binding a reference to a prvalue;

Now number refers to the materialized temporary(xvalue).

Moreover the lifetime of the temporary is extended as can be seen from lifetime

The lifetime of a temporary object may be extended by binding to a const lvalue reference or to an rvalue reference (since C++11), see reference initialization for details.

Jason
  • 36,170
  • 5
  • 26
  • 60
  • But why call it temporary? SInce it is the same as a `const int`? – tempdev nova Jul 15 '22 at 12:16
  • @tempdevnova `10` is a prvalue and temporary materialization will result in an xvalue. Next, `number` will be bound to that resulting `xvalue`. We use the term "temporary" here **because a temporary has been materialized**. – Jason Jul 15 '22 at 12:24
  • *But why call it temporary?* Because it is a **temporary**. *SInce it is the same as a `const int`?* It is **not** the same as a `const int`. You can use it the same way as a `const int`, and likely the compiler will compile it to the same exact machine code. – Eljay Jul 15 '22 at 12:26