const引用可以赋值为int吗?

时间:2012-05-29 15:11:31

标签: c++ memory reference const

我遇到了一个代码段

const int& reference_to_const_int = 20;
cout<<"\n  reference_to_const_int = "<<reference_to_const_int<<endl;     

此代码编译&amp;执行输出: -

reference_to_const_int = 20

这对我来说很奇怪。据我所知,参考不占用记忆和它们是其他变量的别名。因此我们不能说

int& reference_to_int = 30;

以上陈述不得编译给出错误: -

 error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

“const int&amp;”中究竟发生了什么?案件?需要完整的解释。

请帮助。

谢谢

2 个答案:

答案 0 :(得分:11)

创建了一个临时文件,将const引用绑定到它是合法的,但将其绑定到非const引用是非法的。

就像:

const int& reference_to_const_int = int(20);  //LEGAL
      int& reference_to_const_int = int(20);  //ILLEGAL

const引用延长了临时的生命,这就是为什么这样做的原因。这只是语言规则。

答案 1 :(得分:5)

当我们查看绑定对临时对象的引用时会发生什么,这种行为更容易理解。如果我们写

const int& reference_to_const_int = 20; //A temporay object int(20) is created.

编译器将上面的代码转换成如下代码:

int temp = 20;
const int& reference_to_const_int = temp;

如果reference_to_const_int不是const,那么我们可以为reference_to_const_int分配一个新值。这样做不会改变文字20,而是会改变临时对象,因此无法访问。 只允许将const引用绑定到需要临时值的值,完全避免了这个问题,因为const引用是只读的。

为什么C ++允许const引用接受临时对象或RVALUES(如文字)?

我们看到引用最常见的地方是函数参数或返回值。 当引用用作函数参数时,对函数内部引用的任何修改都将导致函数外部参数的更改。

如果函数可以期望/接受临时对象或文字作为输入,并且如果函数遵循对象的常量,则使参数成为const引用将允许在所有情况下使用该函数。

临时对象总是const,因此如果不使用const引用,编译器将不接受该参数。

void f(int&) {}
void g(const int&) {}
int main() 
{
    //f(1); //Error
    g(1); //OK 
}
相关问题