With the placement syntax of the new operator, also known as placement new. Objects are normally created on the stack, on the heap, or in static memory. These correspond to automatic allocation, dynamic allocation, and static allocation, respectively. But these normal techniques don't allow the programmer to specify the exact address at which the object will live. Occasionally an object's desired location is known before the object is created, such as when the hardware uses a piece of storage as a way of communicating with the software. In these cases, placement new can be used. The following example places an object of class Fred at the hexadecimal address 0xFEEDBABE and passes (42, 42) to the Fred constructor. #include "Fred.hpp" <-- 1 #include <new> using namespace std; void sample() { void* place = (void*) 0xFEEDBABE; Fred* p = new(place) Fred(42, 42); // ... }
The storage pointed to by place must be large enough to hold sizeof(Fred) bytes and must be properly aligned to hold a Fred object. The returned pointer p is numerically the same as place, but p is a Fred* rather than a void*. |