Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const rvalue compiler difference

Consider this code:

#include <iostream>


void f(int&& i)
{
    std::cout << "f(int&&)\n";
}

void f(const int&& i)
{
    std::cout << "f(const int&&)\n";
}


int fun_i()
{
    return 0;
}

const int fun_ci()
{
    return 0;
}

int main()
{
    f(fun_i());
    f(fun_ci());
}

If I compile this with MSVC 2012, the output is:

f(int&&)
f(const int&&)

If I compile with GCC 4.7, the output is:

f(int&&)
f(int&&)

Which is correct?

(If I remove the second definition of f, the program will not compile under MSVC 2012, but it does compile under GCC 4.7.)

like image 507
oz1cz Avatar asked Aug 28 '12 13:08

oz1cz


1 Answers

GCC is correct. From paragraph 4 of 3.10 Lvalues and rvalues [basic.lval]:

Class prvalues can have cv-qualified types; non-class prvalues always have cv-unqualified types. [...]

A function call such as fun_ci() is in fact a prvalue*, and as such has type int, not const int. int&& is a better match than const int&&, and should be picked by overload resolution.

*: it's customarily said that top-level cv-qualifiers are ignored for non-class return types.

like image 130
Luc Danton Avatar answered Sep 18 '22 13:09

Luc Danton