【问题标题】:Allocating zero objects with std::allocator::allocate(0) in C++在 C++ 中使用 std::allocator::allocate(0) 分配零个对象
【发布时间】:2018-12-04 10:03:25
【问题描述】:

new int[0] 在 C++ 中是允许的,但 std::allocator<int>().allocate(0) 是否定义明确? 更一般地说,所有分配器都必须接受0 作为分配参数吗?

编辑: 阅读答案后,我测试了 Visual Studio 的std::allocatorallocate(0) 给出了nullptr

deallocate(nullptr, anything) 是一个 nop。

所以使用nullptr 是一个很好的建议,但标准不要求deallocate(nullptr, 0) 是nop,请参阅C++ allocator::deallocate(NULL,1) allowed?

【问题讨论】:

    标签: c++ memory-management language-lawyer dynamic-memory-allocation allocator


    【解决方案1】:

    表 34 - Cpp17Allocator 要求
    为 T 类型的 n 个对象分配了内存,但未构造对象。分配可能 抛出适当的异常。174 [注意:如果 n == 0,则返回值未指定。 ——尾注]

    我认为“分配器应该/应该处理 n == 0,而不是抛出并返回一个可能是有效指针或 nullptr 的值。”

    【讨论】:

    【解决方案2】:

    确实new int[0] 定义明确。请注意,您需要在返回的指针上调用delete[],并且取消引用指针的行为是未定义的。

    类似的规则适用于std::allocator().allocate(0):你不能取消引用返回的指针,你需要通过调用std::allocator::deallocate以正常方式清理内存。

    允许分配器抛出std::bad_alloc 异常;您可以通过这样做来处理 0 参数情况,而不会违反标准规定的任何要求。返回nullptr 是另一种选择。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      • 2012-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多