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?
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.
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.
¶ Δ Probably not. Unless you used placement new , you should simply delete the object rather than explicitly calling the destructor.
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.
Factors:
new[]
must be matched with delete[]
/ new()
with delete
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.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With