隐式转换:const引用vs非const引用与非引用 [英] Implicit conversion : const reference vs non-const reference vs non-reference
问题描述
请考虑此代码,
struct A {};
struct B { B(const A&) {} };
void f(B)
{
cout << "f()"<<endl;
}
void g(A &a)
{
cout << "g()" <<endl;
f(a); //a is implicitly converted into B.
}
int main()
{
A a;
g(a);
}
此编译精细,运行良好。但是如果我把 f(B)
改为 f(B&)
,它不能编译。如果我写 f(const B&)
,它再次编译良好a>,运行良好。为什么是原因和理由?
This compiles fine, runs fine. But if I change f(B)
to f(B&)
, it doesn't compile. If I write f(const B&)
, it again compiles fine, runs fine. Why is the reason and rationale?
摘要:
void f(B); //okay
void f(B&); //error
void f(const B&); //okay
我想从语言规范中听到原因,理由和参考,对于这些情况。当然,函数签名本身并不正确。而 A
隐式转换为 B
和 const B&
但不会进入 B&
,这会导致编译错误。
I would like to hear reasons, rationale and reference(s) from the language specification, for each of these cases. Of course, the function signatures themselves are not incorrect. Rather A
implicitly converts into B
and const B&
, but not into B&
, and that causes the compilation error.
推荐答案
我想听取语言规范中的原因,理由和参考
I would like to hear reasons, rationale and reference(s) from the language specification
em> C ++的设计和进化足够了?
Is The Design and Evolution of C++ sufficient?
我犯了一个严重的错误,引用由非注释[由我评论:该措辞不精确!]初始化。例如:
void incr(int& rr) { ++rr; }
void g()
{
double ss = 1;
incr(ss); // note: double passed, int expected
// (fixed: error in release 2.0)
}
由于类型的不同, int&
不能引用 double
临时生成以保存由 ss
的值初始化的 int
。因此, incr()
修改了临时变量,结果未反映回调用函数 [ emphasis mine ]。
Because of the difference in type the int&
cannot refer to the double
passed so a temporary was generated to hold an int
initialized by ss
's value. Thus, incr()
modified the temporary, and the result wasn't reflected back to the calling function [emphasis mine].
想想一下:调用引用的整个点是客户端传递由函数,函数返回后,客户端必须能够观察到更改。
Think about it: The whole point of call-by-reference is that the client passes things that are changed by the function, and after the function returns, the client must be able to observe the changes.
这篇关于隐式转换:const引用vs非const引用与非引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!