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
Non const lvalue references
提问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;
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.
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?
a
is 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 a
does not change(what's worse, you might think a
has changed, which may cause problems).
你可以修改m
,它绑定了一个临时的,但几乎没有任何反应。修改后,变量a
没有改变(更糟糕的是,你可能认为a
已经改变了,这可能会导致问题)。