zah*_*pov 16 c++ memory-management new-operator
我看到这样的代码:
void *NewElts = operator new(NewCapacityInBytes);
Run Code Online (Sandbox Code Playgroud)
并且明确地匹配调用operator delete随后使用.
为什么这样做而不是:
void *NewElts = new char[NewCapacityInBytes];
Run Code Online (Sandbox Code Playgroud)
为什么显式调用operator new和operator delete??
Cha*_*via 26
operator new像这样明确地调用全局"原始"运算符new.Global operator new返回一个原始内存块,而不调用对象的构造函数或任何用户定义的重载new.所以基本上,全球operator new类似于mallocC.
所以:
// 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));
Run Code Online (Sandbox Code Playgroud)
如果你写:
T *p = new T;
Run Code Online (Sandbox Code Playgroud)
分配足够的内存来保存T,然后将T构造到其中.如果你写:
T *p = ::operator new(sizeof(T));
Run Code Online (Sandbox Code Playgroud)
这会分配足够的内存来保存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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3822 次 |
| 最近记录: |