Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 standard ref for not initializing rvalue reference with lvalue?

Consider the following C++11 code:

int& f();

int&& i = f();

This produces an error:

cannot bind ‘int’ lvalue to ‘int&&’

I understand why, but I'm trying to justify it from the language in the standard.

Paraphrasing C++11 N3485 8.5.3.5:

A reference to int is initialized by an expression of type int as follows: (yes)

If the reference is an rvalue reference: (yes)

If the initializer expression: (yes)

  1. is an xvalue, class prvalue, array prvalue or function lvalue (no?), or
  2. has class type [snip] (no)

Is it the case that neither of these two points apply? So we should just assume it is ill-formed because neither do?

How can you determine from the standard that you can't initialize an rvalue reference to int with an lvalue of type int?

like image 468
Andrew Tomazos Avatar asked Jun 23 '26 07:06

Andrew Tomazos


1 Answers

I think you missed the last bullet of that article (8.5.3p5), that states:

If T1 is reference-related to T2 and the reference is an rvalue reference, the initializer expression shall not be an lvalue.

like image 181
Balog Pal Avatar answered Jun 25 '26 20:06

Balog Pal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!