为什么文字不是const(字符串除外)? [英] Why are literals not const (except strings)?

查看:91
本文介绍了为什么文字不是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(字符串除外)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆