Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cppreference says that copy_n can throw bad_alloc? When is it possible?

Tags:

c++

I've read through copy_n documentation https://en.cppreference.com/w/cpp/algorithm/copy_n and there's an interesting line in Exceptions section:

  • If the algorithm fails to allocate memory, std::bad_alloc is thrown.

What allocation is it talking about?
When we want to copy N bytes we firstly allocate a buffer ourselves with T* buffer = new T[SIZE] and then use copy_n with given SIZE
What situation when copy_n allocates memory exist?

like image 953
IC_ Avatar asked Nov 18 '25 02:11

IC_


1 Answers

This section is talking about the overload with a template parameter named ExecutionPolicy. That overload allows the algorithm to use multiple threads to do the copying. To facilitate that, the implementation might need to allocate some resources and that could throw.

These exceptions do not apply to the serial version of the algorithm.

like image 192
NathanOliver Avatar answered Nov 19 '25 16:11

NathanOliver