[英]why call operator new explicitly
I saw code like this: 我看到这样的代码:
void *NewElts = operator new(NewCapacityInBytes);
And matching call explicitly operator delete
is used consequent later. 并且稍后使用明确的operator delete
匹配调用。
Why do this instead of: 为什么这样做而不是:
void *NewElts = new char[NewCapacityInBytes];
Why explicit call to operator new
and operator delete
?? 为什么显式调用operator new
和operator delete
?
Explicitly calling operator new
like that calls the global "raw" operator new. 明确地调用operator new
就像调用全局“raw”运算符new一样。 Global operator new
returns a raw memory block without calling the object's constructor or any user-defined overloads of new
. 全局operator new
返回原始内存块,而不调用对象的构造函数或任何用户定义的new
重载。 So basically, global operator new
is similar to malloc
from C. 所以基本上,全局operator new
类似于来自C的malloc
。
So: 所以:
// Allocates space for a T, and calls T's constructor,
// or calls a user-defined overload of new.
//
T* v = new T;
// Allocates space for N instances of T, and calls T's
// constructor on each, or calls a user-defined overload
// of new[]
//
T* v = new T[N];
// Simply returns a raw byte array of `sizeof(T)` bytes.
// No constructor is invoked.
//
void* v = ::operator new(sizeof(T));
If you write: 如果你写:
T *p = new T;
That allocates enough memory to hold a T, then constructs the T into it. 分配足够的内存来保存T,然后将T构造到其中。 If you write: 如果你写:
T *p = ::operator new(sizeof(T));
That allocates enough memory to hold a T, but doesn't construct the T. One of the times you might see this is when people are also using placement new: 这会分配足够的内存来保存T,但不会构造T.有时您可能会看到这是人们也在使用新的位置:
T *p = ::operator new(sizeof(T)); // allocate memory for a T
new (p) T; // construct a T into the allocated memory
p->~T(); // destroy the T again
::operator delete(p); // deallocate the memory
If you call operator new(bytesize), then you can delete it using delete, whereas if you allocate via new char[bytesize], then you have to match it using delete[], which is an abomination to be avoided wherever possible. 如果你调用operator new(bytesize),那么你可以使用delete删除它,而如果你通过new char [bytesize]分配,那么你必须使用delete []来匹配它,这是一个可以避免的憎恶。 This is most likely the root reason to use it. 这很可能是使用它的根本原因。
Use it when you want to allocate a block of "raw" memory and don't want anything constructed in that memory. 当您想要分配一块“原始”内存并且不希望在该内存中构造任何内容时,请使用它。
There is little practical difference between allocating a block of raw memory and "constructing" an array of chars but using operator new clearly signals your intent to anyone reading the code which is important. 在分配一块原始内存和“构建”一组字符之间几乎没有什么实际区别,但是使用operator new可以清楚地向任何读取代码的人表达你的意图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.