8

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?

sharptooth
  • 167,383
  • 100
  • 513
  • 979
user541686
  • 205,094
  • 128
  • 528
  • 886

2 Answers2

7

Factors:

  • new[] must be matched with delete[] / new() with delete
  • They communicate different things. operator new(n) is a request for memory for unspecified purposes, whereas new 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 a void* 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