具有 class 类型左值操作数的条件表达式

Conditional expression with class type lvalue operands

如果条件表达式的第二个和第三个操作数是 class 类型的左值,我想弄清楚条件表达式结果的值类别应该是什么。

示例:

struct S {};
S x, y;
void foo(bool cond) {
  cond ? x : y;  // what is the value category of the result?
}

我在 [expr.cond] 中看到两个不同的段落表达了不同的意思。

根据第 4 段:

If the second and third operands are glvalues of the same value category and have the same type, the result is of that type and value category

这一段似乎适用,说结果是左值,因为第二个和第三个操作数都是同一类型的左值。

然而,根据第 6 段:

Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard conversions are performed on the second and third operands. After those conversions, one of the following shall hold:

  • The second and third operands have the same type; the result is of that type. If the operands have class type, the result is a prvalue temporary of the result type, which is copy-initialized from either the second operand or the third operand depending on the value of the first operand.

这段好像也适用,说表达式的结果是右值

那么它是左值还是右值?这两段真的相互矛盾,还是我遗漏了一些微妙的东西?

您必须按顺序阅读段落,select第一个适用。强调我的。

1

...

2

If either the second or the third operand has type void ...

3

Otherwise, if the second and third operand have different types and either has (possibly cv-qualified) class type, or if both are glvalues of the same value category and the same type except for cv-qualification ...

4

If the second and third operands are glvalues of the same value category and have the same type ...

5

Otherwise, the result is a prvalue. If the second and third operands do not have the same type, and either has (possibly cv-qualified) class type, overload resolution is used to determine the conversions (if any) to be applied to the operands (13.3.1.2, 13.6). If the overload resolution fails, the program is ill-formed. Otherwise, the conversions thus determined are applied, and the converted operands are used in place of the original operands for the remainder of this section.

6

Lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are per- formed on the second and third operands. ...