The start of the Standard <new> is defined by a special operator new, which is well known.Placement new. Unlike other common new ones, it has another parameter in brackets. For example:
Widget * p = new Widget; // ordinary
New // common new pi = new (ptr) int;
Pi = new (ptr) int; // placement new
The parameter in the brackets is a pointer pointing to a memory buffer. placement new will assign an object to the buffer. The return value of Placement new is the address of the constructed object (for example, the transfer parameter in the buckle ). Placement
New mainly applies to: In applications with very high time requirements, because the time allocated by these programs is determined; programs that run for a long time without being interrupted; and execute a garbage collector (garbage collector ).
Usage
In many cases, the use of placement new is different from that of other common new ones. The procedure is provided here.
Step 1 cache allocation in advance
To ensure proper preparation of the memory alignmen (memory Queue) in the cache area used by placement new, use the normal new to allocate it:
Class Task;
Char * buff = new [sizeof (Task)]; // allocate memory
(Please note that auto or static memory is not correctly arranged for each object type, so you will not be able to use placement
New uses them .)
Step 2: allocate objects
Call placement new in the allocated cache area to construct an object.
Task * ptask = new (buff) Task
Step 3: Use
Use the allocated object in the normal way:
Ptask-> suspend ();
Ptask-> resume ();
//...
Step 4: Object destruction
Once you use this object, you must call its destructor to destroy it. Call the Destructor as follows:
Ptask-> ~ Task (); // call external destructor
Step 5: Release
You can reuse the cache repeatedly and assign it a new object (Repeat steps 2, 3, 4). If you do not intend to use the cache again, you can release it like this:
Delete [] buff;
Skipping any step may cause the running time to crash, memory leakage, and other unexpected situations. If you do need placement new, follow these steps carefully.
Danny Kalev, a 14-year-old system analyst and software engineer, specializes in C ++ and visual object programming.