There are no cases I can think of where it allocates memory that isnt immediately usable. |
cppreference.com has the example about placement new:
1 2 3 4 5 6 7 8 9 10 11 12
|
char* ptr = new char[sizeof(T)]; // allocate raw memory
// formally, you have an array of char
T* tptr = new(ptr) T; // construct in allocated storage ("place")
// now you have a properly created T object
// use tptr
// alas, explicit destruction is required
tptr->~T(); // destruct
delete[] ptr; // deallocate raw memory
|
Yes, the
new []
on line 1 does both allocate memory and "create objects", but those objects are simple
char
, whose "constructor" (and destructor) is trivial.
Yes, that block memory is immediately usable as array of char.
However, the intent here is not to use an array. The intent is to use a T object. There creation -- proper initialization of T is delayed to line 4. T is a complex object, whose internal state is intricate.
The
placement new does not allocate memory. It merely calls the constructor of a class.
We can do it.
The same page refers to class
Allocator
that encapsulates the use of placement new.
You can give a custom Allocator to std containers. For example, to change how std::vector manages memory.
Why would you do that?
Dynamic memory allocation is relatively slow; the system has to find a suitable block from heap and do accounting. What if you know how you will need memory and allocate a big block for all your needs,
once at start of a procedure?
Then use placement new (via allocators) to construct and destruct objects within that block. You obviously have to do the "seek&account" yourself, but IF your use case is clear, then your specific implementation can be more efficient than the generic OS heap.