其中使用 - “操作员新”或“operator new []” - 在C ++中分配一个原始内存块? [英] Which to use - "operator new" or "operator new[]" - to allocate a block of raw memory in C++?
问题描述
我的C ++程序需要一个未初始化的内存块和一个 void *
指向该块的指针,以便我可以将它提供给第三方库。我想将块生存期的控制传递给库,所以我不想使用 std :: vector
。当库完成块,它将调用我必须提供的回调,并将释放该块。在CI中将使用 malloc()
和更高版本 free()
。
My C++ program needs a block of uninitialized memory and a void*
pointer to that block so that I can give it to a third party library. I want to pass control of the block lifetime to the library, so I don't want to use std::vector
. When the library is done with the block it will call a callback that I have to supply and that will deallocate the block. In C I would use malloc()
and later free()
.
在C ++中,我可以调用 :: operator new
或 :: operator new []
和 :: operator delete
或操作符delete []
分别以后:
In C++ I can either call ::operator new
or ::operator new[]
and ::operator delete
or operator delete[]
respectively later:
void* newBlock = ::operator new( sizeOfBlock );
// then, later
::operator delete( newBlock );
看起来像 :: operator new
:: operator new []
具有完全相同的签名和完全相同的行为。对于 :: operator delete
和 :: operator delete []
也是如此。我不应该做的唯一的配对 operator new
与 operator delete []
,反之亦然 - 未定义的行为。除此之外,我选择哪对,为什么?
Looks like both ::operator new
and ::operator new[]
have exactly the same signature and exactly the same behavior. The same for ::operator delete
and ::operator delete[]
. The only thing I shouldn't do is pairing operator new
with operator delete[]
and vice versa - undefined behavior. Other than that which pair do I choose and why?
推荐答案
使用单个对象和使用
与对象数组。因此,例如: new
> new []
Use new
with a single object and new[]
with an array of objects. So, for example:
int* x = new int; // Allocates single int
int* y = new int[5]; // Allocates an array of integers
*x = 10; // Assignment to single value
y[0] = 8; // Assignment to element of the array
如果你正在做的就是分配一个内存缓冲区,然后分配一个 char
如:
int bufferlen = /* choose a buffer size somehow */
char* buffer = new char[bufferlen];
// now can refer to buffer[0] ... buffer[bufferlen-1]
你应该真正使用 std :: vector
任意数组,你应该使用 std :: string
However, in C++, you should really use std::vector
for arbitrary arrays, and you should use std::string
for character arrays that are to be interpreted or used as strings.
没有理由调用 :: operator new
或 :: operator new []
,而不是使用这些调用的普通语法。对于POD和原始类型(例如 char
),不会进行初始化。如果你需要一个 void *
缓冲区,那么只需使用 static_cast
来转换 char *
到 void *
。
There is no reason to invoke ::operator new
or ::operator new[]
explicitly rather than using the ordinary syntax for these calls. For POD and primitive types (e.g. char
) no initialization will take place. If you need to get a void*
buffer, then simply use static_cast
to convert char*
to void*
.
这篇关于其中使用 - “操作员新”或“operator new []” - 在C ++中分配一个原始内存块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!