Many questions on SO ask about placement new feature of C++ (example 1, example 2) why it is used for. Many answers saying - custom allocating of objects like in pre-allocated spaces.
But question is - why need placement new for this? Won't just overload of operator new for class enough? By overload operator new for class I can exactly control where memory taken from - like call custom allocator. So why would I need placement new for this purpose?
Best example is to think about std::vector
How does std::vector put new items into an array?
When you add a new element to the end of an vector it must use placement new.
class MyVector
{
char* data;
size_t size;
MyVector() : size(0), data(new char[1000]) {}
// Placement new copy construction of element into array.
void push_back(T const& t) { new (data + (sizeof(T) * size)) T(t); ++size;}
};
Remember you can not use assignment or a simple copy because the element does not yet exist in the array (ie the memory space is not yet a T (its value is not defined)) so you must new to create a new T object in the array.
So think of placement new as a means of creating container objects. You can allocate more space than required for the container (and not initialize it). Then use placement new to initialize the elements as they are added.
Overloading new allows you to control the space used when object have dynamic storage duration
. Maybe your expected usage patterns do not fall under the normal usage patterns and you want to optimize creation/destruction. Maybe you want you want to build your own garbage collection (for a particular type).
The main different is that:
Both are corner cases for the language and rarely used in normal code (I think I have written 2 new overloads and one class that uses placement new (for real production code/ does not include experiments and testing) in 15 years).
By the time you need to use these constructs in real life you will have been working with an experienced team for a couple of years that can validate your design.
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