分配失败时,C ++ allocator :: allocate抛出还是返回nullptr? [英] Should C++ allocator::allocate throw or return nullptr when allocation fails?

查看:232
本文介绍了分配失败时,C ++ allocator :: allocate抛出还是返回nullptr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

分配器概念 std :: allocator_traits 不说 allocate 会做什么

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

When I'm writing a container using standard allocator API, should I


  1. 检查返回值并在 noexcept 版本成员函数中捕获异常(例如 push_back 调整大小 ...);

  1. Check the return value and catch the exception in the noexcept version member function(E.g. push_back, resize...);

检查返回值并抛出异常,如果失败则抛出该异常

Check the return value and throw if fail in the exception-throwing one

这样,无论是否抛出异常得到正确的行为。

so that no matter it throws or not, I will get the correct behavior.

推荐答案

草稿n4659(对于C ++标准)说的是23.10.9。默认分配器[default.allocator](强调我的):

Draft n4659 for C++ standard says at 23.10.9 The default allocator [default.allocator] (emphasize mine):


23.10.9.1分配器成员[allocator.members]

...

23.10.9.1 allocator members [allocator.members]
...

T* allocate(size_t n);

2返回:指向大小为n * sizeof(T的存储数组的初始元素的指针),将
对齐为T类型的对象。

3备注:通过调用:: operator new(21.6.2)获得存储空间,但何时或$ b $未指定存储空间b该函数的调用频率。

4 抛出:如果无法获得存储,则抛出bad_alloc。

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 异常。

It makes it clear that the standard allocator will raise a bad_alloc exception if it cannot allocate storage.

以上是标准分配器。 20.5.3.5分配器要求[allocator.requirements]和表31 —分配器要求包含对任何分配器的要求:

Above is for the standard allocator. The requirement for any allocator are described in 20.5.3.5 Allocator requirements [allocator.requirements] and table 31 — Allocator requirements contains:


a。 allocate(n)[返回类型:] X ::指针[断言/注释/
前置/后置条件]内存分配给n个类型为T的
个对象,但对象不是
建。分配可能会导致
抛出适当的
异常

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

我的理解是分配仅在分配了内存后才能返回。因此,如果无法分配内存,分配器应该抛出一个适当的异常(即使非常合适也不一定要 bad_alloc )。

My understanding is that allocate can return only when memory has been allocated. So the allocator should throw an appropriate exception (not necessarily bad_alloc even if it would be quite appropriate) if memory could not be allocated.

这篇关于分配失败时,C ++ allocator :: allocate抛出还是返回nullptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆