c++ - 预递增字符串文字

标签 c++ language-lawyer

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/

相关文章:

c++ - 在复制初始化中,对复制构造函数的调用是显式的还是隐式的?

c++ - 为什么在使用大括号初始值设定项列表时首选 std::initializer_list 构造函数?

c++ - 非pod结构查找表

c++ - 请澄清术语类静态对象(与类静态成员)

c++ - 我对 §3.3.2/6 中的单词 'first' 的解释是否正确?

当最大成员是原始类型时, union 是否可以大于最大成员?

c++ - 我如何遍历目录并识别或省略 NTFS 连接(symlink-ish)

c++ - Qt Opengl VBO 数据损坏

c++ - 错误 : call of overloaded 'stoi(nlohmann::basic_json<>::value_type&)' is ambiguous

python - Python 中的字节总是八位字节吗?