1

Consider this piece of code:

struct A {
  bool f() { return true; }
};

// ...
std::vector<A*> v = {new A(), nullptr, new A()};
std::find_if(v.begin(), v.end(), [](const A* object) { return object->f(); });

If we invoke a method from nullptr object, is this an undefined behaviour? If yes and I want to resolve this issue, will it suffice to add A != nullptr in the beginning, so that the condition short-circuits before the potentially dangerous code would be executed?

Inter Veridium
  • 147
  • 1
  • 6

1 Answers1

2

As per this post, yes, that would result in undefined behaviour.

If you wish to avoid the undefined behaviour, which happens if the code attempts to do something which is not defined by the standard, then yes, you will avoid UB if the code doesn't execute, which can be avoided with a condition.

Maurycyt
  • 676
  • 3
  • 19