gpt4 book ai didi

c++ - 为什么::operator new[] 是必需的,而::operator new 就足够了?

转载 作者:太空宇宙 更新时间:2023-11-04 12:42:29 24 4
gpt4 key购买 nike

我们知道,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/53528694/

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