简体   繁体   English

非 const 左值引用

[英]Non const lvalue references

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.更具体地说,我试图了解非常量引用无法绑定临时对象的原因。

That is because a temporary can not bind to a non-const reference.那是因为临时不能绑定到非常量引用。

double &m = a;

a is of type int and is being converted to double . aint类型,正在转换为double So a temporary is created.所以临时创建了。 Same is the case for user-defined types as well.用户定义的类型也是如此。

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.但在 Visual Studio 中,由于默认启用编译器扩展,它运行良好。 But GCC will complain.但是海湾合作委员会会抱怨。

Because making modification on a temporary is meaningless, c++ don't want you to bind non-const reference to a temporary.因为对临时对象进行修改是没有意义的,所以 C++ 不希望您将非常量引用绑定到临时对象。 For example.例如。

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

What if it works?如果有效呢? a is of type int and is being converted to double. a是 int 类型,正在转换为 double。 So a temporary is created.所以临时创建了。

You can modify m , which is bound to a temporary, but almost nothing happens.After the modification, variable a does not change(what's worse, you might think a has changed, which may cause problems).你可以修改m ,它绑定了一个临时的,但几乎没有任何反应。修改后,变量a没有改变(更糟糕的是,你可能会认为a改变了,这可能会导致问题)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM