I just learned about the C++ construct called "placement new". It allows you to exactly control where a pointer points to in memory. It looks like this:
#include <new> // Must #include this to use "placement new"
#include "Fred.h" // Declaration of class Fred
void someCode()
{
char memory[sizeof(Fred)];
void* place = memory;
Fred* f = new(place) Fred(); // Create a pointer to a Fred(),
// stored at "place"
// The pointers f and place will be equal
...
}
(example from C++ FAQ Lite)
In this example, the this
pointer of Fred will be equal to place
.
I've seen it used in our team's code once or twice. In your experience, what does this construct enable? Do other pointer languages have similar constructs? To me, it seems reminiscent of equivalence
in FORTRAN, which allows disparate variables to occupy the same location in memory.
seems to me like a way of allocating an object on the stack ..
I use this construct when doing C++ in kernel mode.
I use the kernel mode memory allocator and construct the object on the allocated chunk.
All of this is wrapped in classes and functions, but in the end I do a placement new.
I've used it to create objects based on memory containing messages received from the network.
Placement new can be used to create type-safe unions, such as Boost's
variant
.The union class contains a buffer as big as the biggest type it's specified to contain (and with sufficient alignment). It placement
new
s objects into the buffer as required.Placement new allows the developer to allocate the memory from preallocated memory chunk. If the system is larger, then developers go for using placement new. Now I am working on a larger avionics software there we allocate the large memory that is required for the execution of application at the start. And we use the placement new to allocate the memory wherever required. It increases the performance to some amount.
It can be useful when paging out memory to a file on the hard drive, which one might do when manipulating large objects.