考虑这段代码:
#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());
}
如果我用 MSVC 2012 编译它,输出是:
f(int&&)
f(const int&&)
如果我用 GCC 4.7 编译,输出是:
f(int&&)
f(int&&)
哪个是正确的?
(如果我删除 f 的第二个定义,程序将无法在 MSVC 2012 下编译,但可以在 GCC 4.7 下编译。)
最佳答案
海湾合作委员会是正确的。来自 3.10 左值和右值 [basic.lval] 的第 4 段:
Class prvalues can have cv-qualified types; non-class prvalues always have cv-unqualified types. [...]
fun_ci()
等函数调用实际上是纯右值*,因此具有类型 int
,而不是 const int
。 int&&
比 const int&&
更匹配,应该由重载决议选择。
*:习惯上说,对于非类返回类型,顶级 cv 限定符将被忽略。
关于c++ - Const 右值编译器区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12160782/