gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:19:21 27 4
gpt4 key购买 nike

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

编辑:
阅读答案后,我测试了 Visual Studio 的 std::allocator :allocate(0)nullptrdeallocate(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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com