I'm allocating memory that will later be used for constructing objects with placement new
. Should I be using operator new(n)
, or should I be using new unsigned char[n]
? Why?
Asked
Active
Viewed 409 times
8

sharptooth
- 167,383
- 100
- 513
- 979

user541686
- 205,094
- 128
- 528
- 886
-
1I think either would do just fine. – Joseph Mansfield May 13 '13 at 09:37
-
@sftrabbit: So there's no difference, in terms of alignment, semantics, performance, or something like that? – user541686 May 13 '13 at 09:37
-
@Mehrdad *"semantics"* - Exactly there's the difference. – Christian Rau May 13 '13 at 10:37
2 Answers
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.

Tony Delroy
- 102,968
- 15
- 177
- 252
5
The former returns a pointer to some storage area. The latter returns a pointer to the first element of an array with some objects in it. If you need storage, use the one that gives storage and not objects.

R. Martinho Fernandes
- 228,013
- 71
- 433
- 510
-
What's the difference? Aren't they both uninitialized? Or are you just saying it's a readability issue? – user541686 May 13 '13 at 09:39
-
1@Elazar No. No object gets initialized with `operator new[n]`. `new unsigned char[n]` default-initializes an array of `unsigned char` (and the default initialization of `unsigned char` performs no initialization). – R. Martinho Fernandes May 13 '13 at 09:45
-
@Elazar: neither are initialised - Standard references provided in my answer. – Tony Delroy May 13 '13 at 10:02
-
-
-
@R.MartinhoFernandes: Ah lol okay, I thought you were responding to me with the wrong name, since I didn't see any other person commenting lol. – user541686 May 13 '13 at 10:08