JiaHao Xu
JiaHao Xu

Reputation: 2748

Should C++ allocator::allocate throw or not?

The Allocator concept and std::allocator_traits doesn't say whether allocate will throw or not.

So when I'm writing a container using allocators, how to know whether to check return type or use catch?

Upvotes: 2

Views: 1170

Answers (2)

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38773

The table in the Requirements section of the page you reference gives quite enough information when it may throw exceptions and when it must not throw exceptions. Below is a quote when an allocator may throw exceptions.

a.allocate(n) allocates storage suitable for n objects of type T, but does not construct them. May throw exceptions.

What type of exceptions is thrown is not described there and maybe is implementation dependent. Generally it is std::bad_alloc in STL.

Upvotes: 4

con ko
con ko

Reputation: 1416

Yes, it may throw. And the exception is std::bad_alloc since it use the allocator passed to it while std::allocator will throw std::bad_alloc.

In the page you refered introduces two scenarios:

  1. Calls a.allocate(n)
  2. Additionally passes memory locality hint hint. Calls a.allocate(n, hint) if possible. If not possible (e.g. a has no two-argument member function allocate()), calls a.allocate(n)

so basically you can turn to this:

http://en.cppreference.com/w/cpp/memory/allocator/allocate

Upvotes: 2

Related Questions