使用三元运算符初始化引用变量
Using ternary operator to initialize a reference variable?
抛开所有的可维护性和读取问题不谈,这些代码行能产生未定义的行为吗?
float a = 0, b = 0;
float& x = some_condition()? a : b;
x = 5;
cout << a << ", " << b;
不,没关系。它不会在此代码中创建未定义的行为。您只需根据条件将a或b的值更改为5即可。
只要条件的两边都是可用于初始化引用(例如变量、指针取消引用等)的表达式,这是绝对可以的。
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
相关文章:
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 为什么初始化时没有调用重载赋值运算符?
- 使用运算符"="在C++中用值初始化对象
- 由于没有使用赋值运算符,映射的值是如何初始化的?
- 当返回语句时,逗号运算符、大括号初始化列表和 std::unique_ptr 组合在一起
- 在未初始化的变量上使用复合赋值运算符(+=, ..)不是C++中的UB?
- std::unordered_map 运算符 [] 是否对非现有密钥进行零初始化?
- 在C++中,为什么int可以使用new运算符初始化变量,而double不能
- 未找到匹配的运算符删除;如果初始化引发异常,内存将不会被释放
- C++ 类型 'complex<double>' 中类中的复杂初始化不提供调用运算符
- 模板流运算符重载错误:引用初始化无效,与basic_istream和basic_ifstream之间的差异有关
- 统一初始化是隐式发生的,即使 int 强制转换运算符是使用 explicit 关键字声明的.原因是什么?
- 在不放置新运算符的情况下,在预分配的内存上使用虚函数初始化对象 - 这可能吗?如果没有,为什么
- 复制 CTOR 与赋值运算符以初始化对象(性能)
- 为什么我可以在不使用赋值运算符的情况下使用列表初始化普通数组
- 使用三元运算符初始化类对象错误
- 使用三元运算符初始化引用变量
- 使用new运算符初始化数组
- 使用相等运算符初始化对象
- 使用和不使用新运算符初始化对象