const引用可以赋值int? [英] const reference can be assigned an int?
问题描述
我遇到了一个代码片段。
I came across a code snippet
const int& reference_to_const_int = 20;
cout<<"\n reference_to_const_int = "<<reference_to_const_int<<endl;
此代码编译&执行输出: -
This code compiles & executes with output :-
reference_to_const_int = 20
这对我来说很奇怪。因为我知道参考不占用记忆&它们是其他变量的别名。因此我们不能说
This is something strange in for me. As I know reference do not occupy memory & they are aliases to other variables. hence we cannot say
int& reference_to_int = 30;
上面的语句不会编译给出错误: -
The above statement shall not compile giving error :-
error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
发生在const int&案件?需要完整的说明。
What exactly is happening in the "const int&" case? A full explanation is desired.
请帮忙。
感谢
推荐答案
创建了一个临时的,绑定一个 const
引用是合法的,一个非 const
一个。
A temporary is created, and it's legal to bind a const
reference to it, but illegal to bind it to a non-const
one.
就像:
const int& reference_to_const_int = int(20); //LEGAL
int& reference_to_const_int = int(20); //ILLEGAL
A const
生命的临时,这就是为什么这样工作。这只是语言的规则。
A const
reference extends the life of a temporary, that's why this works. It's just a rule of the language.
这篇关于const引用可以赋值int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!