加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么在引用文字时必须使用const引用

发布时间:2020-12-16 09:59:42 所属栏目:百科 来源:网络整理
导读:我知道只有对象可以参考.但文字不是对象. 所以我能理解为什么以下代码无法编译: int a = '4';int b = 2; 但是,当我在他们面前添加const时,它可以工作!! const int a = '4';const int b = 2; 我不知道为什么.谁能帮助我? 解决方法 整数或字符文字是prvalue
我知道只有对象可以参考.但文字不是对象.
所以我能理解为什么以下代码无法编译:

int &a = '4';
int &b = 2;

但是,当我在他们面前添加const时,它可以工作!!

const int &a = '4';
const int &b = 2;

我不知道为什么.谁能帮助我?

解决方法

整数或字符文字是prvalue [expr.prim.general]

A literal is a primary expression. Its type depends on its form (2.13). A string literal is an lvalue; all other literals are prvalues.

因为它是一个prvalue我们被允许采取const&它,但我们不能参考它.如果我们采取const&临时的,临时的生命周期将扩展到引用超出范围的点.

{
    const int & a = 42;
    //line of code
    //42 still exits here
} // a goes out of scope and now 42 is gone

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读