为什么文字不是const(字符串除外)?

编程入门 行业动态 更新时间:2024-10-10 08:25:52
本文介绍了为什么文字不是const(字符串除外)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

文学通常是prvalue. 字符串是一种特殊情况,定义为char(意为lvalue)数组. 这个问题专门针对非字符串文字.

Literals are, in general, prvalues. Strings are a special case, defined as an array of char (meaning lvalue). This question is specifically about not string literals.

为什么非字符串文字不是const?

Why are non-string literals not const?

foo(42); // passes foo an `int`, not a `const int`.

您无法修改非字符串文字,因此将其设为const并不合理吗?

You can't modify a non-string literal, so doesn't it make sense for it to be const?

推荐答案

字面意义的答案可能是因为字面值要早于在语言中添加const的位置,因此自然不是const.

The literal answer is probably because literals predate the addition of const to the language, so naturally they are not const.

但是实际的答案是-const pr值本质上是奇怪的东西.您不能从任何基本类型创建它们,但是可以具有类类型的const prvalue.但为什么?通常,我们将事物设为const以防止进一步的修改.但是,如果这是一个prvalue,那么它甚至都不是具有身份的东西-谁将在那里观察它的意想不到的修改? const prvalue防止移动-因为它们是const,所以您不能从它们上移动,因此过早地感到悲观.

But the practical answer is - const prvalues are fundamentally strange things. You cannot create them from any of the fundamental types, but you can have a const prvalue of class type. But... why? Typically, we make things const to prevent further modifications right. But if it's a prvalue, it's not even a thing with identity - who is going to be there to observe its unintended modification? const prvalues prevent moving - because they're const, so you can't move from them, so its a premature pessimization.

请注意,该语言已经明确禁止可能出错的情况,即假设的const文字会阻止该情况:

Note that the one thing that could go wrong, that a hypothetical const literal would prevent, is already explicitly forbidden by the language:

void foo(int&); foo(42); // error

但不是使42 const成为语言,而是使左值引用成为非const的语言,不允许绑定到右值.

But rather than making 42 const, the language made lvalue references non-const not allowed to bind to rvalues.

更多推荐

为什么文字不是const(字符串除外)?

本文发布于:2023-11-24 14:24:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1625574.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   文字   const

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!