[英]What's the difference between overloading operator new and operator new[] in C++?
The operator new
and operator new[]
has the same function prototype: void * (size_t size)
. operator new
和operator new[]
具有相同的函数原型: void * (size_t size)
。 What should I pay attention to when I'm going to overload them? 要让它们超载时应该注意什么?
Is that OK if I only overload operator new
? 如果我只重载operator new
吗?
And what's the difference between overload operator delete
and operator delete[]
? 重载operator delete
和operator delete[]
什么区别?
operator new
is used for creating single object, such as: operator new
用于创建单个对象,例如:
my_class* p = new my_class;
operator new[]
is used for creating object's array, such as: operator new[]
用于创建对象的数组,例如:
my_class* p = new my_class[10];
Is that OK if I only overload operator new? 如果我只重载运算符,那可以吗?
It depends on if you need special treatment for array version ( operator new[]
). 这取决于您是否需要对数组版本( operator new[]
)进行特殊处理。 By default operator new[]
will call operator new
. 默认情况下, operator new[]
将调用operator new
。
Basically, if you need to overload operator new
, it's better to overload operator new[]
too, because if you want to implement your own memory management, it's a good idea to keep them all consistent. 基本上,如果您需要重载operator new
,也最好重载operator new[]
,因为如果您要实现自己的内存管理,则使它们保持一致是一个好主意。 And don't forget the nothrow and placement version(as member functions only, the global version can't be displaced). 并且不要忘记nothrow和placement版本(仅作为成员函数,不能替换全局版本)。
The same is true for operator delete
and operator delete[]
. operator delete
和operator delete[]
也是如此。
new creates an instance, whereas new[] creates a an array. new创建一个实例,而new []创建一个数组。
new[] will almost have little memory overhead compared to new to store the size of the array. 与new相比,new []几乎没有什么内存开销来存储数组的大小。
You can't use non-default constructors with new[]. 您不能将非默认构造函数与new []一起使用。
new must be used with delete. new必须与delete一起使用。
new[] must be used with delete[]. new []必须与delete []一起使用。
another Difference: 另一个区别:
new[] is an operator to allocate and initialize an array of objects and return a pointer to the first element. new []是用于分配和初始化对象数组并返回指向第一个元素的指针的运算符。
This differs from the new operator which has the same behavior but for one allocation, not an array 这不同于具有相同行为但有一个分配而不是数组的new运算符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.