当:: operator new足够时,为什么:: operator new []是必需的? [英] Why is ::operator new[] necessary when ::operator new is enough?

查看:57
本文介绍了当:: operator new足够时,为什么:: operator new []是必需的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道,C ++标准定义了两种形式的全局分配函数:

As we know, the C++ standard defines two forms of global allocation functions:

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

而且,C ++标准草案(18.6.1.2 n3797)表示:

And also, the draft C++ standard (18.6.1.2 n3797) says:

227)这不是操作员的直接责任 新的或运算符删除以记下重复 数组的数量或元素大小.这些操作已执行 数组中其他位置的new和delete表达式.数组新 表达式,但是,可能会增加运算符的size参数 以获得存储补充信息的空间.

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)怎么办?定义冗余全局分配函数的理由是什么?

What if we remove void* operator new[](size_t); from the standard, and just use void* operator new(size_t) instead? What's the rationale to define a redundant global allocation function?

推荐答案

我认为::operator new[]可能对于相当专业的系统很有用,在该系统中,大而少"数组可以由与小而众"不同的分配器分配对象.但是,目前它是一个遗物.

I think ::operator new[] may have been useful for fairly specialized systems where "big but few" arrays might be allocated by a different allocator than "small but numerous" objects. However, it's currently something of a relic.

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

operator new can reasonably expect that an object will be constructed at the exact address returned, but operator new[] cannot. The first bytes of the allocation block might be used for a size "cookie", the array might be sparsely initialized, etc. The distinction becomes more meaningful for member operator new, which may be specialized for its particular class.

在任何情况下,::operator new[]都不是非常必要的,因为std::vector(通过std::allocator)(当前是获取动态数组的最流行方法)会忽略它.

In any case, ::operator new[] cannot be very essential, because std::vector (via std::allocator), which is currently the most popular way to obtain dynamic arrays, ignores it.

在现代C ++中,自定义分配器通常比自定义operator new更好.实际上,应该完全避免使用new表达式,而应该使用容器类(或智能指针等),因为此类提供了更多的异常安全性.

In modern C++, custom allocators are generally a better choice than customized operator new. Actually, new expressions should be avoided entirely in favor of container (or smart-pointer, etc) classes, which provide more exception safety.

这篇关于当:: operator new足够时,为什么:: operator new []是必需的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆