gpt4 book ai didi

c++ - 关于左值到右值的转换,什么时候需要?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:35:58 28 4
gpt4 key购买 nike

我在网上看了很多,好像很多人都提到了下面的规则(但我在标准中找不到),

加法运算符 +(以及所有其他二元运算符)要求两个操作数都是右值,结果也是右值。等等..

我查看了 C++ 标准,它明确指出(条款 3.10/2),

Whenever a glvalue appears in a context where a prvalue is expected, the glvalue is converted to a prvalue

(第 5/9 条),

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.

它使用一个术语,操作数“期望”一个纯右值。然而,当我查看加法运算符、乘法运算符等时,它只提到结果是纯右值,但没有说明操作数是“预期”的。

二元运算符是否真的期望操作数是纯右值在以下情况下会有所不同,

int b = 2;
int a = b + 1;

如果b期望是prvalue,这里会进行左值到右值的转换,然后执行prvalue + prvalue返回一个prvalue,结果prvalue赋给一个左值a。

但是,如果 b 不需要是纯右值,则它将是左值 + 纯右值,结果是纯右值。

我真的很想知道标准在哪里明确或隐含地提到了不同运营商的规则?我检查了所有运算符部分,只有少数运算符标准明确提到操作数和结果是左值还是右值。对于大多数运算符,标准仅提及结果而未提及操作数要求。

谢谢。


顺便说一句,我在标准 5.19 中发现关于常量表达式的内容可能非常非常“隐含地”暗示二元运算符需要对操作数进行左值到右值的转换。更多详情,请引用我之前的问题,

mixing use of constexpr and const?

A conditional-expression is a constant expression unless it involves one of the following as a potentially evaluated subexpression (3.2).

...

— an lvalue-to-rvalue conversion (4.1) unless it is applied to

———— a glvalue of integral or enumeration type that refers to a non-volatile const object with a preceding initialization, initialized with a constant expression

感谢阅读。

最佳答案

因此,这通常是标准的那些推断和不明确的部分之一;然而,在 3.10

[ Note: some built-in operators expect lvalue operands. [ Example: built-in assignment operators all expect their left-hand operands to be lvalues. — end example ] Other built-in operators yield rvalues, and some expect them. [ Example: the unary and binary + operators expect rvalue arguments and yield rvalue results. — end example ] The discussion of each built-in operator in clause 5 indicates whether it expects lvalue operands and whether it yields an lvalue. — end note ]

请注意“在第 5 条中指示它是否需要左值操作数以及它是否产生左值”的不明确的语言。

第 5 章的检查表明,每个表达式需要或返回左值的情况都被枚举,但是很少有专门处理右值的情况被枚举,我认为然后假定其余的被假定为右值。

我还怀疑它的指定不当,因为从标准的角度来看,转换是由运算符隐式或显式完成的并不是特别重要,无论如何,行为应该是一致且行为良好的。

关于c++ - 关于左值到右值的转换,什么时候需要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5099769/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com