gpt4 book ai didi

c++ - 分配失败时 C++ allocator::allocate 应该抛出还是返回 nullptr?

转载 作者:太空狗 更新时间:2023-10-29 20:09:00 25 4
gpt4 key购买 nike

Allocator conceptstd::allocator_traits不要说当分配失败时 allocate 会做什么——它会返回 nullptr 还是抛出异常?

当我使用标准分配器 API 编写容器时,我应该

  1. 检查返回值并捕获noexcept版本成员函数中的异常(例如push_back, resize...) ;

  2. 检查返回值,在异常抛出处抛出失败

这样无论抛出与否,我都会得到正确的行为。

最佳答案

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] 和表 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只有在分配内存后才能返回。因此,如果无法分配内存,分配器应该抛出一个适当的异常(不一定是 bad_alloc,即使它非常合适)。

关于c++ - 分配失败时 C++ allocator::allocate 应该抛出还是返回 nullptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50326564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com