FAQ 12.14 How is an object constructed at a predetermined position in memory?

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);   // ... } 

(1) Pretend this defines class Fred

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*.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net