我正在分配内存,稍后将用于构造带有放置的对象new
。我应该使用operator new(n)
,还是应该使用new unsigned char[n]
?为什么?
问问题
370 次
2 回答
7
Factors:
new[]
must be matched withdelete[]
/new()
withdelete
- They communicate different things.
operator new(n)
is a request for memory for unspecified purposes, whereasnew unsigned char[n]
loosely implies intent to store characters there.
The array form may be slightly worse performance / efficiency wise - exact details depending on your implementation:
5.3.4/12 new T[5] results in a call of operator new where x is a non-neagtive unspecified value representing array allocation overhead: the result of the new-expression will be offset by this amount from the value returned by
operator new[]
....
BTW - neither are initialised:
operator new()
returns avoid*
to uninitialised memory: see 3.7.4.1/2 "There are no constraints on the contents of the allocated storage on return from the allocation function", whereas 5.3.4/15 says "a new-expression that creates an object of type T initializes that object as follows: if the new-initializer is ommitted, the object is default-initialized (8.5)"; 8.5/6 says only class types default constructors provide initialisation.
于 2013-05-13T09:45:15.153 回答
5
前者返回一个指向某个存储区域的指针。后者返回一个指向包含一些对象的数组的第一个元素的指针。如果您需要存储,请使用提供存储而不是对象的存储。
于 2013-05-13T09:38:44.563 回答