N3337 标准草案的 § 2.14.5/8 指出:
Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration (3.7).
§ 4.2
An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The result is a pointer to the first element of the array.
我期望 ++"hello world!"
将 "hello world!"
衰减为 char*
但这并没有发生。必须使用额外的加号 +++"hello world!"
强制执行。有些情况下不应用数组到指针的转换,例如 sizeof
运算符。
§ 5.3.2 简单地说:
The operand of prefix ++ is modified by adding 1, or set to true if it is bool (this use is deprecated). The operand shall be a modifiable lvalue. The type of the operand shall be an arithmetic type or a pointer to a completely-defined object type. The result is the updated operand; it is an lvalue, and it is a bit-field if the operand is a bit-field. If x is not of type bool, the expression ++x is equivalent to x+=1
那么为什么没有发生这种转化呢?
最佳答案
当需要将左值转换为纯右值时,将应用数组到指针(和其他衰减)转换,按照 5/8:
Whenever a glvalue expression appears as an operand of an operator that expects a prvalue for that operand, the lvalue-to-rvalue (4.1), array-to-pointer (4.2), or function-to-pointer (4.3) standard conversions are applied to convert the expression to a prvalue.
请注意,根据您自己对 5.3.2 的引用,++
的操作数必须是可修改的左值。数组到指针的转换用于将 glvalue 转换为 prvalue,这不是 ++
所需要的。因此,没有什么需要数组到指针的转换。应用它实际上是无效的,因为该转换的结果是纯右值,++
不能对其执行操作。
关于c++ - 预递增字符串文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27375117/