C++ 非 const 左值引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18565167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:01:59  来源:igfitidea点击:

Non const lvalue references

c++

提问by Mars

Why can you do this

为什么你可以这样做

int a;
const double &m = a;

But when you do this

但是当你这样做时

int a;
double &m = a;

you get an error?

你有错误吗?

error: non-const lvalue reference to type 'double' cannot bind to a value of unrelated type 'int'

Edit:

编辑:

To be more specific I am trying to understand the reason non-const references can't bind temp objects.

更具体地说,我试图了解非常量引用无法绑定临时对象的原因。

采纳答案by Mahesh

That is because a temporary can not bind to a non-const reference.

那是因为临时不能绑定到非常量引用。

double &m = a;

ais of type intand is being converted to double. So a temporary is created. Same is the case for user-defined types as well.

a是 类型int并且正在转换为double. 所以临时创建了。用户定义的类型也是如此。

Foo &obj = Foo(); // You will see the same error message.

But in Visual Studio, it works fine because of a compiler extension enabled by default. But GCC will complain.

但在 Visual Studio 中,由于默认启用编译器扩展,它运行良好。但是海湾合作委员会会抱怨。

回答by xinnjie

Because making modification on a temporary is meaningless, c++ don't want you to bind non-const reference to a temporary. For example.

因为对临时对象进行修改是没有意义的,所以 C++ 不希望您将非常量引用绑定到临时对象。例如。

int a;
double &m = a;  // caution:this does not work.

What if it works? ais of type int and is being converted to double. So a temporary is created.

如果有效呢? a是 int 类型,正在转换为 double。所以临时创建了。

You can modify m, which is bound to a temporary, but almost nothing happens.After the modification, variable adoes not change(what's worse, you might think ahas changed, which may cause problems).

你可以修改m,它绑定了一个临时的,但几乎没有任何反应。修改后,变量a没有改变(更糟糕的是,你可能认为a已经改变了,这可能会导致问题)。