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

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

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/

相关文章:

c++ - 如何使用OutputDebugString添加指针

java - 合法线程 Action 的定义

c++ - 为什么我无法编译这个简单的线程测试?

c++ - 内联调用不太可能失败,代码大小会增加 [-Winline] 但不使用内联

c++ - 将 make_shared 与 shared_ptr<T> 一起使用仅对 T < 56 字节有益?

python - 在 Python 中读取 Parquet 时内存使用率过高

c++ - GCC对尖括号的实现包括。为什么必须如下所述?

c++ - 转换常量表达式定义的澄清

c++ - 无法使用 ifstream 读取 txt 文件

c++ - 初始化并存储在另一个类中的对象是否应该动态/静态分配?