new int[0]
在 C++ 中是允许的,但 std::allocator<int>().allocate(0)
定义好?
更一般地说,所有分配器都必须接受 0
作为参数分配?
编辑:
阅读答案后,我测试了 Visual Studio 的 std::allocator
:allocate(0)
给 nullptr
deallocate(nullptr, anything)
是一个nop。
所以使用 nullptr
是个好建议,但标准不要求deallocate(nullptr, 0)
是一个 nop,见 C++ allocator::deallocate(NULL,1) allowed?
最佳答案
Table 34 — Cpp17Allocator requirements
Memory is allocated for n objects of type T but objects are not constructed. allocate may throw an appropriate exception.174 [Note: If n == 0, the return value is unspecified. —end note]
我会读为“分配器应该/应该处理
n == 0
,而不是抛出并返回一个可能是有效指针或 nullptr
的值。”
关于c++ - 在 C++ 中使用 std::allocator::allocate(0) 分配零个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53610332/