三元运算的结果(类型)是什么?

what is the result (type) of ternary operation?

三元运算return是复制还是引用?

我检查了以下代码

vector<int> v0 = { 1, 2 };
vector<int> v1 = { 3 };

vector<int>& v = true ? v0 : v1;
v.clear(); // v0 will be cleared also

我认为三元运算 return 是 v0 的副本。然后传给v。因此 vv0 具有不同的数据存储方式。测试未显示。

谢谢,Kerrek SB!我添加了一个 "should-not-compiled" 示例(感谢 WhiZTiM!)来说明这一点。

vector<int>& v = true ? v0 : vector<int>{3};
v.clear(); // v0 will not be cleared

条件表达式的类型是操作数的普通类型

但我认为您实际上对此并不感兴趣。重要的是条件表达式的值类别是什么。

如果两个操作数都是或可以转换为普通类型的左值,则条件表达式是左值;否则它是一个右值(可能需要对其中一个操作数进行左值到右值的转换)。

找到规则here: 与您的表达相关:

E1 ? E2 : E3

4) If E2 and E3 are glvalues of the same type and the same value category, then the result has the same type and value category, and is a bit-field if at least one of E2 and E3 is a bit-field.

你的情况:

true ? v0 : v1;

v0v1lvalues (broadly glvalue)。 所以 return 将是一个 lvalue v0。因此,您的表达式将等同于:

vector<int>& v = v0;

至于你的编辑

vector<int>& v = true ? v0 : vector<int>{3};
v.clear(); // v0 will not be cleared

Should not compile,因为结果的值类别将是 rvalue,并且您不能将 非常量引用 绑定到 rvalue