为什么不能非引用临时对象? [英] Why not non-const reference to temporary objects?

查看:122
本文介绍了为什么不能非引用临时对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:



Possible Duplicate:
Does a const reference prolong the life of a temporary?
prolonging the lifetime of temporaries

C ++允许将临时对象仅分配给const引用。它不允许分配临时对象来引用。

C++ allows assignment of temporary objects only to const reference. It wont allow assignement of temporary objects to reference.

例如:

String& a = String("test");         // Error
const String& a = String("test");   // Ok

到这个结果,我只能看到以下答案

Everywhere I google for this result, i only see the following answers


  1. 修改临时对象会导致无法识别的问题

  2. 修改临时对象是危险的

  3. 在某个时间点,你会忘记它是一个临时变量

据说,临时对象在语句后消失。所以你不应该修改它。

It's been said, temporary objects vanishes after the statement. So you should not modify it.

如果C ++如此热衷于阻止修改临时对象,它应该阻止读取临时对象?如果临时对象消失了,那么从那里读取内容没有意义?

If C++, is so keen in blocking modifying the temporary objects, it should have blocked reading the temporary objects right? If the temporary object is vanished, then there is no point in reading contents from there right? The possible cases, where a right can occur, could also involve the read too.

那么为什么它一直阻塞写和允许读?

Then why its been blocking write alone and allowing read?

请给我一个固定的c ++代码解释。

Please give me a solid c++ code explanation.

请不要指出一些选择。请给我坚实的答案代码为什么const int&是允许的,int&不允许用于临时对象。

Please dont deviate the question by pointing some alternatives. Please give me solid answer with code why const int & is allowed and int & is not allowed for temporary objects.

一个说&&是有..我的问题不同..
换句话说,改变不会反映..改变不会反映,即使是const int&太。例如:double a; Const int& i = a; a ++;不会影响i ..

One says && is there.. My question different.. ANother say,changing will not reflect.. Changing will not reflect even when it is const int & too. Eg: double a; Const int & i = a; a++; will not affect i..

推荐答案

不允许引用临时表的原始情况是函数参数。假设这是允许的:

The original case for not allowing references to temporaries was for function parameters. Suppose this was allowed:

void inc(double& x)
{ x += 0.1; }

int i = 0;
inc(i);

为什么 i

这篇关于为什么不能非引用临时对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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