正如标题所说:c++标准是否保证&&
(或and
)运算符的左侧总是首先求值?老实说,我不能在c++ 17标准中搜索,我不知道我应该找哪个部分。
问题示例:
我想这样做:
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…与
&
不同,&&
保证从左到右求值:如果第一个操作数为假,则不对第二个操作数求值。