将所有可维护性和阅读问题放在一边,这些代码行是否会产生未定义的行为?
float a = 0, b = 0;
float& x = some_condition()? a : b;
x = 5;
cout << a << ", " << b;
答案 0 :(得分:10)
答案 1 :(得分:8)
这是绝对正常的,只要条件的两边都是可用于初始化引用的表达式(例如变量,指针解引用等)
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