why must use const reference when reference to literals

旧城冷巷雨未停 提交于 2019-12-01 22:07:08

A integer or character literal is a 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.

Since it is a prvalue we are allowed to take a const & to it but we cannot take a reference to it. If we take a const & to the temporary the the lifetime of the temporary will be extended to the point where the reference goes out of scope.

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

(Assiming that you left out '&' in the second snippet.)

Because the literal is not an object; a temporary object is created which has the value corresponding to the literal.

You can bind a temporary to a const reference, and thereby extend that object's lifetime, but you can't bind it to a non-const reference.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!