非常量左值引用 [英] Non const lvalue references

查看:62
本文介绍了非常量左值引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要这么做

int a;
const double &m = a;

但是当您这样做时

int a;
double &m = a;

您遇到错误吗?

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

编辑:

更具体地说,我试图了解非const引用不能绑定临时对象的原因。 / p>

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

推荐答案

这是因为临时对象无法绑定到非const引用。

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

double &m = a;

a 类型为 int 并被转换为 double 。这样就创建了一个临时文件。用户定义类型也是如此。

a is of type int and is being converted to 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.

但是在Visual Studio中,由于默认启用了编译器扩展,因此可以正常工作。但是海湾合作委员会会抱怨。

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

这篇关于非常量左值引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆