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

问题描述

和不说 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):

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:

我的理解是分配仅在分配了内存后才能返回。因此,如果无法分配内存,分配器应该抛出一个适当的异常(即使非常合适也不一定要 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 23:30