18

抛开所有的可维护性和阅读问题,这些代码行会产生未定义的行为吗?

float  a = 0, b = 0;
float& x = some_condition()? a : b;
x = 5;
cout << a << ", " << b;
4

2 回答 2

12

不,这很好。它不会在此代码中创建未定义的行为。您只需根据条件将 a 或 b 的值更改为 5。

于 2012-07-15T19:39:51.127 回答
9

这绝对没问题,只要条件的两边都是可用于初始化引用的表达式(例如变量、指针取消引用等)

float& x = some_condition()? a : *(&b); // This is OK - it is the same as your code
float& x = some_condition()? a : b+1;   // This will not compile, because you cannot take reference of b+1
于 2012-07-15T19:42:05.680 回答