【发布时间】:2016-12-14 09:52:56
【问题描述】:
我一定是误解了auto c++11 及更高版本如何解析类型。我有以下代码:
void foo(int& x)
{
++x;
}
int main()
{
int i = 2;
int& ir = i;
long L = 5;
auto a = ir/L;
foo(a);
return 0;
}
这会导致编译器错误:
test.cpp: In function 'int main()':
test.cpp:12:10: error: invalid initialization of non-const reference
of type ‘int&’ from an rvalue of type ‘int’
foo(a);
^
test.cpp:1:6: note: initializing argument 1 of ‘void foo(int&)’
void foo(int& x)
^~~
但是,将 auto 替换为 int (int a = ir/L;) 可以正常编译并给出预期的结果(在调用 foo() 之前的 a == 0 和之后的 a == 1)。在玩弄代码并看到各种错误消息后,我认为auto 被推导出为long int&。定义函数void bar(int x) 和void bar(const int& x) 会导致错误消息:call of overloaded ‘bar(long int&)’ is ambiguous。
来自 cmets 的更正:
我不明白auto x = [int&]/[int] 是如何产生一个可以由非常量引用传递的左值,而auto x = [int&]/[long] 产生一个不能被传递的右值。
【问题讨论】:
-
a不是参考,它是一个简单的long。 -
^^^^^^Yup, it's just
long -
如果你不明白为什么它很长,原因是类型提升。你应该read the answer to this
-
我必须同意,如果没有错误,错误消息会产生误导。它应该是
invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘long’。 VS2015的报错信息更有帮助:'void foo(int &)': cannot convert argument 1 from 'long' to 'int &' -
当您认为
x很长时,该错误非常有意义。要将其传递给需要int(或int&)的函数,需要创建一个临时(右值)int。而且它不能绑定到非常量引用。
标签: c++ c++11 reference c++14 auto