在条件运算符中使用对象两次会产生 UB 吗?

Does using an object in conditional operator twice yield UB?

据我所知,条件运算符(三元运算符“?”)保证了其操作数的求值顺序我想知道是否将 return 或 ? 赋值给变量] 其中这个变量用在它的两个表达式之一中。是不是UB。这是我拥有的:

我编写了这个程序,它试图根据字符串 str 是否包含有效数字字符将字符串转换为整数,例如:+-.0123456789,所以我使用了 std::stoistd::string::find_first_of 和条件运算符组合在一个表达式中:

std::string str = "a^%^&fggh67%$hf#$";
std::size_t pos = 0;
auto val = (((pos = str.find_first_of("0123456789.+-")) != std::string::npos) ?
    std::stoi(str.substr(pos)) : -1);

std::cout << val << std::endl; // 67

str = "a^%^&fggh__#$!%$hf#$";
pos = 0;
val = (((pos = str.find_first_of("0123456789.+-")) != std::string::npos) ?
    std::stoi(str.substr(pos)) : -1);

std::cout << val << std::endl; // -1

如您所见,这段代码看起来运行良好,我知道如果在 str 中意外找到值 -1,我们不知道 val 是否成立-1 操作成功或失败(?运算符)。但是我只想知道我写的这段代码有没有UB?

代码没有未定义的行为。条件运算符由 [expr.cond]/1 定义为

Conditional expressions group right-to-left. The first expression is contextually converted to bool. It is evaluated and if it is true, the result of the conditional expression is the value of the second expression, otherwise that of the third expression. Only one of the second and third expressions is evaluated. Every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second or third expression.

强调我的

因此,((pos = str.find_first_of("0123456789.+-")) != std::string::npos) 被求值,一个序列点是 "reached",然后根据结果 std::stoi(str.substr(pos))-1 在其自己的序列表达式中求值。