gpt4 book ai didi

c++ - 隐式转换 : const reference vs non-const reference vs non-reference

转载 作者:可可西里 更新时间:2023-11-01 17:38:33 28 4
gpt4 key购买 nike

考虑这段代码,

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);
}

compiles fine ,运行良好。但是,如果我将 f(B) 更改为 f(B&),它 doesn't compile .如果我写f(const B&),它又是compiles fine ,运行良好。原因和道理是什么?

总结:

void f(B);         //okay
void f(B&); //error
void f(const B&); //okay

对于每种情况,我想听听语言规范中的原因、基本原理和引用资料。当然,函数签名本身并没有错。 A 隐式转换为 Bconst B&,但不会转换为 B&,这会导致编译错误。

最佳答案

I would like to hear reasons, rationale and reference(s) from the language specification

C++ 的设计和演进是否足够?

I made one serious mistake, though, by allowing a non-const reference to be initialized by a non-lvalue [comment by me: that wording is imprecise!]. For example:

void incr(int& rr) { ++rr; }

void g()
{
double ss = 1;
incr(ss); // note: double passed, int expected
// (fixed: error in release 2.0)
}

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].

想想看:call-by-reference 的全部意义在于客户端传递被函数改变的东西,函数返回后,客户端必须能够观察到变化.

关于c++ - 隐式转换 : const reference vs non-const reference vs non-reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4704404/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com