使用三元运算符初始化引用变量?

Ali*_*232 15 c++ reference ternary-operator

抛开所有可维护性和读取问题,这些代码行是否会产生不确定的行为?

float  a = 0, b = 0;
float& x = some_condition()? a : b;
x = 5;
cout << a << ", " << b;
Run Code Online (Sandbox Code Playgroud)

Blo*_*ood 10

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


das*_*ght 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
Run Code Online (Sandbox Code Playgroud)