分配失败时 C++ allocator::allocate 应该抛出还是 return nullptr?
Should C++ allocator::allocate throw or return nullptr when allocation fails?
Allocator concept and std::allocator_traits 没有说当分配失败时 allocate
会做什么——它会 returns nullptr 还是抛出?
当我使用标准分配器 API 编写容器时,我应该
检查return值,在noexcept
版本成员函数中捕获异常(如push_back
、resize
...);
检查return值,如果失败则抛出异常抛出
这样无论抛出与否,我都会得到正确的行为。
C++ 标准草案 n4659 在 23.10.9 默认分配器 [default.allocator](强调我的):
23.10.9.1 allocator members [allocator.members]
...
T* allocate(size_t n);
2 Returns: A pointer to the initial element of an array of storage of size n * sizeof(T), aligned
appropriately for objects of type T.
3 Remarks: the storage is obtained by calling ::operator new (21.6.2), but it is unspecified when or
how often this function is called.
4 Throws: bad_alloc if the storage cannot be obtained.
清楚地表明,如果标准分配器无法分配存储空间,它将引发 bad_alloc
异常。
以上是标准分配器。 20.5.3.5 分配器要求 [allocator.requirements] 和 table 中描述了对任何分配器的要求 31 — 分配器要求包含:
a.allocate(n) [Return type:] X::pointer [Assertion/note/
pre-/post-condition]Memory is allocated for n
objects of type T but objects are
not constructed. allocate may
throw an appropriate
exception
我的理解是allocate
只能在分配内存的情况下才能return。因此,如果无法分配内存,分配器应该抛出一个适当的异常(不一定 bad_alloc
即使它非常合适)。
Allocator concept and std::allocator_traits 没有说当分配失败时 allocate
会做什么——它会 returns nullptr 还是抛出?
当我使用标准分配器 API 编写容器时,我应该
检查return值,在
noexcept
版本成员函数中捕获异常(如push_back
、resize
...);检查return值,如果失败则抛出异常抛出
这样无论抛出与否,我都会得到正确的行为。
C++ 标准草案 n4659 在 23.10.9 默认分配器 [default.allocator](强调我的):
23.10.9.1 allocator members [allocator.members]
...T* allocate(size_t n);
2 Returns: A pointer to the initial element of an array of storage of size n * sizeof(T), aligned appropriately for objects of type T.
3 Remarks: the storage is obtained by calling ::operator new (21.6.2), but it is unspecified when or how often this function is called.
4 Throws: bad_alloc if the storage cannot be obtained.
清楚地表明,如果标准分配器无法分配存储空间,它将引发 bad_alloc
异常。
以上是标准分配器。 20.5.3.5 分配器要求 [allocator.requirements] 和 table 中描述了对任何分配器的要求 31 — 分配器要求包含:
a.allocate(n) [Return type:] X::pointer [Assertion/note/ pre-/post-condition]Memory is allocated for n objects of type T but objects are not constructed. allocate may throw an appropriate exception
我的理解是allocate
只能在分配内存的情况下才能return。因此,如果无法分配内存,分配器应该抛出一个适当的异常(不一定 bad_alloc
即使它非常合适)。