三元运算的结果(类型)是什么? [英] what is the result (type) of ternary operation?
问题描述
三元操作是否返回副本或引用?
Does the ternary operation return a copy or reference?
我检查了以下代码
vector<int> v0 = { 1, 2 };
vector<int> v1 = { 3 };
vector<int>& v = true ? v0 : v1;
v.clear(); // v0 will be cleared also
我认为三元运算会返回 v0
。然后将其传递给 v
。因此, v
和 v0
具有不同的数据存储。测试没有显示出来。
I think the ternary operation returns a copy of v0
. And then pass it to v
. Thus v
and v0
has different storage of data. Testing doesn't show it.
谢谢,Kerrek SB!我添加了一个不应该编译的示例(感谢WhiZTiM!)来说明这一点。
Thanks, Kerrek SB! I add a "should-not-compiled" example (Thanks WhiZTiM!) to show the point.
vector<int>& v = true ? v0 : vector<int>{3};
v.clear(); // v0 will not be cleared
推荐答案
条件表达式的类型是操作数的常见类型。
The type of a conditional expression is the common type of the operands.
但是我认为您实际上对此并不感兴趣。重要的是条件表达式的值类别是什么。
But I think you aren't actually interested in that. What matters is what the value category of a conditional expression is.
如果两个操作数都是或可以转换为公共的左值类型,则条件表达式为左值;否则为右值(可能需要将其中一个操作数从左值转换为右值)。
If both operands are, or can be converted to, lvalues of the common type, then the conditional expression is an lvalue; otherwise it is an rvalue (potentially requiring lvalue-to-rvalue conversion of one of the operands).
这篇关于三元运算的结果(类型)是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!