c++ - const 引用可以分配一个 int 吗?

标签 c++ memory reference constants

我遇到了一个代码片段

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

此代码编译并执行输出:-

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&”的情况下到底发生了什么?需要一个完整的解释。

请帮忙。

谢谢

最佳答案

创建了一个临时对象,将 const 引用绑定(bind)到它是合法的,但将其绑定(bind)到非 const 引用是非法的。

就像:

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

const 引用延长了临时对象的生命周期,这就是它起作用的原因。这只是语言的规则。

关于c++ - const 引用可以分配一个 int 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10801894/

相关文章:

c++ - 对象内的 Valgrind 数组溢出

python - 用最少的内存连接 Numpy 数组

java - 管理文件java上的大数组

c++ - 使用优先级队列时出现段错误

javascript - Mongoose 子文档 : cannot call method call to of undefined

c++ - 如何替换具有 double 类型的模板参数?

c++ - 如何从类中包装的成员访问包装类的成员

c++ - 在范围中使用对 vector 元素的引用

c++ - 为什么构造函数没有被调用

c++ - 我可以在 MacBook Pro 上分配的最大内存量是多少?