在C ++中用std :: allocator :: allocate(0)分配零个对象

Oll*_*erg 5 c++ memory-management allocator dynamic-memory-allocation language-lawyer

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

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

deallocate(nullptr, anything) 是点头。

因此,使用nullptr是一个很好的建议,但是标准不要求deallocate(nullptr, 0)是nop,请参见是否允许使用C ++ allocator :: deallocate(NULL,1)?

Bat*_*eba 3

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

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

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