-2

As the title says: Is there any guarantee from C++ Standard to be sure the left side of && (or and) operator always evaluated first? To be honest, I couldn't search in C++17 Standard, I don't know which section I most look for.

Sample of Problem:

I want to do something like this:

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;
}

And want to be sure there is no problem with the code.

Ghasem Ramezani
  • 2,683
  • 1
  • 13
  • 32

1 Answers1

5

[expr.log.and]/1 ... Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
  • With the caveat that a user-defined `operator&&` does not have this short-circuit behavior. And a recommendation to avoid making one's own user-defined `operator&&`. – Eljay Feb 14 '21 at 20:01