Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the result (type) of ternary operation?

Does the ternary operation return a copy or reference?

I checked the following code

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

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

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.

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
like image 368
user1899020 Avatar asked Feb 22 '17 15:02

user1899020


1 Answers

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).

like image 59
Kerrek SB Avatar answered Oct 30 '22 09:10

Kerrek SB