Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator new(n) versus new unsigned char[n] for placement new

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?

like image 250
user541686 Avatar asked May 13 '13 09:05

user541686


People also ask

What is placement new operator?

Placement new is a variation new operator in C++. Normal new operator does two things : (1) Allocates memory (2) Constructs an object in allocated memory. Placement new allows us to separate above two things. In placement new, we can pass a preallocated memory and construct an object in the passed memory.

What is :: operator new?

The operator new (or better the void* operator new(size_t) variant) just allocate memory, but does not do any object construction. The new keyword calls the operator new function, but then calls the object constructor.

Does placement new call destructor?

¶ Δ Probably not. Unless you used placement new , you should simply delete the object rather than explicitly calling the destructor.

What is new operator C++?

When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated. Use the delete operator to deallocate the memory allocated by the new operator.


2 Answers

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.
like image 56
Tony Delroy Avatar answered Oct 11 '22 08:10

Tony Delroy


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.

like image 24
R. Martinho Fernandes Avatar answered Oct 11 '22 09:10

R. Martinho Fernandes