0

I am confused about std::unique_ptr and std::make_unique as far as exception is concerned.

I believe unique_ptr is noexcept but make_unique can actually throw an std::bad_alloc.

In case I have this on the .hpp file:

std::unique_ptr<MATRIX[]> matrix; 

And I will call this on the .cpp file:

std::make_unique<MATRIX[]>(256);
  1. Is there a chance that allocation will actuall fail?
  2. Should I add a handling in case allocation fails?
  3. How should the code look like then if I will add an exception handling?

Thanks!

kzaiwo
  • 1,558
  • 1
  • 16
  • 45
  • Yes, allocation could fail. See the linked question for answers to 2 and 3 (in short: don't bother handling `std::bad_alloc`). – John Kugelman Jun 27 '19 at 09:33
  • Stand back and think about it for a moment. You are running on a computer with _finite memory_. At some point in time, when you have no idea how much of that _finitie memory_ has been used you try to allocate some memory. Is it possible that the allocation will fail? Of course - its impossible to guarantee it wont. – Mike Vine Jun 27 '19 at 09:43
  • Thank you for your answers! So is it okay (standard or something) to NOT catch these ```std::bad_alloc``` exceptions anymore? There is so many ```std::make_unique``` calls in the code and I feel like it is so messy to put in ```throw-catch``` statements for all these allocations. – kzaiwo Jun 27 '19 at 10:17
  • In general handling OOM errors is out of scope for most general purpose programs - its both very hard to actually achieve (so many things can fail when you're low on memory and you pretty much must handle them all) and its hard to actually do anything useful once you've detected it - you have no memory to anything useful in. (Yes there are programs where this is useful but they're rare). So my recommendation would be to insta-die on OOM. – Mike Vine Jun 27 '19 at 10:53
  • If you *were* going to catch it, you still wouldn't want to surround every allocation with a try/catch block. You would let the exception propagate up the call stack, perhaps even all the way to `main()`. – John Kugelman Jun 27 '19 at 11:13

0 Answers0