是否有任何保证确保始终首先评估 && 运算符的左侧?
Is there any guarantee to be sure the left side of && operator is always evaluated first?
正如标题所说:C++ 标准是否有任何保证确保 &&
(或 and
)运算符的左侧始终首先计算?老实说,我无法在C++17 Standard中搜索,我不知道我最想找哪个部分。
问题示例:
我想做这样的事情:
std::unordered_map<std::size_t, std::weak_ptr<T>> objects;
bool f (std::size_t const id) {
bool result = false;
if (not objects.at(id).expired()) {
auto const& object = objects.at(id).lock();
/* Here left side of `and` most be evaluated first */
result = object->parent->remove(id) and
objects.erase(id) == 1;
}
return result;
}
并且想确定代码没有问题。
[expr.log.and]/1 ... Unlike &
, &&
guarantees left-to-right
evaluation: the second operand is not evaluated if the first operand is false.
正如标题所说:C++ 标准是否有任何保证确保 &&
(或 and
)运算符的左侧始终首先计算?老实说,我无法在C++17 Standard中搜索,我不知道我最想找哪个部分。
问题示例:
我想做这样的事情:
std::unordered_map<std::size_t, std::weak_ptr<T>> objects;
bool f (std::size_t const id) {
bool result = false;
if (not objects.at(id).expired()) {
auto const& object = objects.at(id).lock();
/* Here left side of `and` most be evaluated first */
result = object->parent->remove(id) and
objects.erase(id) == 1;
}
return result;
}
并且想确定代码没有问题。
[expr.log.and]/1 ... Unlike
&
,&&
guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.