Reference semantics of a conditional statement

I played using lvalue as a result of a conditional statement ( cond ? expr1 : expr2 ).

Consider the following example.

 class /*(1)*/ Value { public int MagicNumber { get; private set; } = 0; public void Increment() { /* magical code, that modifies MagicNumber */ } } void Main() { Value v1, v2; /*(2)*/ bool condition = /*...*/; (condition ? v1 : v2).Increment(); // (3) } 

Now I would suggest that based on the value of condition , either v1 or v2 is incremented. This is true if Value ( (1) ) is a class. As soon as I change it to struct , it becomes a value type, and line (3) does nothing (I suspect that either v1 or v2 copied, incremented and discarded). Before that it makes sense. Strange behavior begins after (2) ( condition ) is known at compile time (for example, by defining its const bool ). Then some optimization appears, and one of v1 or v2 actually increases in place.

My question is: what should be the correct behavior of the conditional operator in the following case

 (condition ? v1 : v2).Increment(); 

once v1 and v2 is equal to struct . Should it depend on the condition compile-time constant?

+5
source share
1 answer

As I said, I sent a bug report to Microsoft, and it turned out that the standard does not explicitly indicate whether the result of the conditional operator is r (value) or l-value (variable). By the transitivity of other things in the standard, it seems that the result should be an r-value .

It was decided that the error should be fixed, and the correction is already on this path.

+1
source

Source: https://habr.com/ru/post/1265336/


All Articles