Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can std::find_if potentially fail with std::bad_alloc exception?

Tags:

c++

stl

As I stated in the title, I just can't understand why does this function throw std::bad_alloc. If we take a look at the cppreference all of the three possible implementations are just as someone would assume and it looks like there is no special need dynamic memory allocation.

like image 379
Godra Avatar asked Sep 12 '25 17:09

Godra


1 Answers

The 3 possible implementations shown in cppreference are for the 3 overloads that do not take an execution policy. It is specifically the overloads that do take an execution policy that are specifically listed as possibly throwing std::bad_alloc.

Execution policy involves the possibility of parallelizing or vectorizing the operation. That would require extra memory to pull off rather than just relying on the scalar variables in the non parallelized/vectorized version.

Edit: That said, as @user17732522 said in comments:

The default is that a standard library function without noexcept specification is allowed to throw implementation-defined exceptions (see eel.is/c++draft/res.on.exception.handling#4) and find_if doesn't have any "Throws:" clause constraining that (eel.is/c++draft/alg.find).

So an implementation is allowed to provide a std::find that does throw for any of the overloads.

like image 186
Avi Berger Avatar answered Sep 15 '25 07:09

Avi Berger