有一个单独的“operator new []”的目的是什么? [英] What's the purpose of having a separate "operator new[]"?

查看:107
本文介绍了有一个单独的“operator new []”的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来像 operator new operator new [] 具有完全相同的签名:

Looks like operator new and operator new[] have exactly the same signature:

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

并执行完全相同的操作:返回一个指针到一个足够大的原始

and do exactly the same: either return a pointer to a big enough block of raw (not initialized in any way) memory or throw an exception.

当我创建一个对象时,内部调用 operator new code> new 和 operator new [] - 当我创建一个对象数组 new [] 。仍然上面的两个特殊函数是由C ++在内部以完全相同的方式调用,我不知道这两个调用如何具有不同的意义。

Also operator new is called internally when I create an object with new and operator new[] - when I create an array of objects with new[]. Still the above two special functions are called by C++ internally in exactly the same manner and I don't see how the two calls can have different meanings.

具有完全相同的签名和完全相同的行为的两个不同的函数?

What's the purpose of having two different functions with exactly the same signatures and exactly the same behavior?

推荐答案

,Stroustrup提到如果对象X的新运算符本身用于分配对象X的数组,那么X :: operator new()的作者也必须处理数组分配,这不是新的()并增加复杂性。所以,它不被认为使用new()进行数组分配。然后,没有简单的方法为动态数组分配不同的存储区域。解决方案是为数组提供单独的allocator和deallocator方法:new []和delete []。

In Design and Evolution of C++ (section 10.3), Stroustrup mentions that if the new operator for object X was itself used for allocating an array of object X, then the writer of X::operator new() would have to deal with array allocation too, which is not the common usage for new() and add complexity. So, it was not considered to use new() for array allocation. Then, there was no easy way to allocate different storage areas for dynamic arrays. The solution was to provide separate allocator and deallocator methods for arrays: new[] and delete[].

这篇关于有一个单独的“operator new []”的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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