A very important feature of C ++ is flexibility, and even the memory can be operated to control the location of variables in the memory. Placement new is used to allocate memory of the specified size on the specified address.
When placement new is used, the header file new must be included. Its prototype is void * operator new (size_t, void * P );. The syntax format is (optional ):
[Yourtype * pvalue =] New (Address) yourtype [(parameters)]
When calling, the system allocates memory with address as the starting address and calls the corresponding constructor of yourtype. Return address.
Examples:
Void * Buf = reinterpret_cast <void *> (0xf00f); <br/> X * P2 = new (BUF) X;
Placement new can also use different allocation functions for different classes. We can customize the allocation function as needed.
Class arena {<br/> Public: <br/> virtual void * alloc (size_t) = 0; <br/> virtual void free (void *) = 0; <br/> //... <br/>}; <br/> void * operator new (size_t S, arena * A) {<br/> A-> alloc (s ); <br/>}< br/> extern arena * Persistent; <br/> void g (int I) {<br/> X * P = new (persistent) X (I); // X in persistent storage <br/>}
Note that the operator new function is different from other operator functions (such as operator =). It does not overload the new (or delete) expression, and we cannot redefine the behavior of the New and delete expressions.
The standard library contains the operator new function and operator delete function, which can be used to obtain unconstructed memory. This is also the first step for memory allocation using the new expression (when the new expression is used to allocate memory, the first step is to call the standard operator new function to allocate uninitialized memory, the second step is to call the appropriate constructor, and the third step is to return the pointer to the constructed object ).
The memory allocated using placement new is not controlled by the standard memory management program. You need to manually call the destructor to release the memory space.
Void destroy (x * P, arena * A) {<br/> P-> ~ X (); <br/> A-> free (p); <br/>}
(Reference: The C ++ programming language)