c++ - 当::operator new 足够时,为什么需要::operator new[]?

标签 c++ memory-management overloading standards new-operator

众所周知,C++ 标准定义了两种形式的全局分配函数:

void* operator new(size_t);
void* operator new[](size_t);

此外,C++ 标准草案 (18.6.1.2 n3797) 说:

227) It is not the direct responsibility of operator new or operator delete to note the repetition count or element size of the array. Those operations are performed elsewhere in the array new and delete expressions. The array new expression, may, however, increase the size argument to operator new to obtain space to store supplemental information.

让我困惑的是:

如果我们从标准中删除 void* operator new[](size_t); 并只使用 void* operator new(size_t) 会怎样?定义冗余全局分配函数的基本原理是什么?

最佳答案

我认为 ::operator new[] 对于相当专业的系统可能很有用,其中“大而少”的数组可能由与“小而多”的对象不同的分配器分配。然而,它目前是一个遗物。

operator new 可以合理地期望对象将在返回的确切地址处构造,但 operator new[] 不能。分配 block 的第一个字节可能用于大小“cookie”,数组可能被稀疏初始化,等等。这种区别对于成员 operator new 变得更有意义,它可能专门针对其特​​定类。

无论如何,::operator new[] 并不是非常必要的,因为 std::vector(通过 std::allocator ),这是目前最流行的获取动态数组的方式,忽略它。

在现代 C++ 中,自定义分配器通常比自定义 operator new 更好。实际上,应该完全避免 new 表达式以支持容器(或智能指针等)类,它们提供更多的异常安全性。

关于c++ - 当::operator new 足够时,为什么需要::operator new[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24603142/

相关文章:

c++ - vector 的模式匹配/识别库(如用于图像输入的 OpenCV)

c++ - 为大节点树动态分配内存

assembly - 内存寄存器如何用于保存不同的类型?

c++ - 在派生中使用额外的默认参数重载基类方法

python - python 中 __truediv__ 的运算符重载

c++ - 如何处理 boost::program_options 中的未经请求的参数

c++ - 删除类对象的转换函数?

c++ - 在指针的多态数组中删除和对象

objective-c - 在 iOS 6 中学习 ARC 的资源

c++ - 模板和重载