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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With