Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The type of 'i' below in main(). Why is it an int&?

I know the type of i below in main() is an int&. That's why it must be initialized.

int& f(){ static int i = 1; return i; }

int main()
{
    decltype(f()) i = f();
}

But using paragraph 5p5 in the Standard, I conclude that the expression f() has type int as the reference is dropped.

From 7.1.6.2p4, how can one say that the expression f() is an lvalue, given that the reference was dropped from the function return?

like image 385
Ayrosa Avatar asked May 27 '13 14:05

Ayrosa


1 Answers

The reference is dropped when evaluating the type of the expression (as per § 5/5), but this does not change the fact that the function call expression f() is an lvalue. Per paragraph 5.2.2/10 of the C++11 Standard:

A function call is an lvalue if the result type is an lvalue reference type or an rvalue reference to function type, an xvalue if the result type is an rvalue reference to object type, and a prvalue otherwise.

In other words, the reference is not dropped from the return type of the function itself, only from the type of the evaluated function call expression (which is, therefore, int).

The fact that the function is returning an lvalue reference is what allows the type system to classify corresponding function call expressions as lvalues - which, in turn, allows decltype to add the lvalue reference to the type of the expression, thus yielding int&.

like image 190
Andy Prowl Avatar answered Nov 10 '22 09:11

Andy Prowl