Placement New (positioning new)

xiaoxiao2021-03-06  111

Location Place New (Placement New) has a lot. The easiest place is to place objects in the special location in memory. This is done by the location of the pointer parameters of the New Expression section:

#include // must be included in #include to use "Placement New" #include "Fred.h" // Class Fred "{char memory () {char memory () {char memory [sizeof (fred)]; // line # 1 Void * Place = Memory; // Line # 2 Fred * f = new (place) Fred (); // Line # 3 (see "Danger" below) /////////. ..} LINE # 1 Create an array of SIZEOF (FRED) bytes in memory, enough to put down the Fred object. Line # 2 Created a PLACE pointer to this memory (experienced C programmer) This step is redundant, just in order to make the code more obvious). Line # 3 is essentially called constructor fred :: fred (). The Modifier in the Fred constructor will be equal to Place. Therefore, the returned F will be equal to Place.

Recommendation: If you don't have to use the "Placement New" syntax. Only use it when you really care about the specific location in memory. For example, your hardware has a memory image I / O timer device, and you want to place a clock object in that memory location.

DANG: You have to bear such responsibility alone, the memory area points to the pointer to the "Placement New" operator must be large enough, and may need to be bounded to the object created. There is no attempt to check if you do correct when compiler and runtime system. If the Fred class needs to adjust the boundary to 4 bytes, and if the location you provide, you will make a serious disaster (if you don't understand the meaning of "boundary adjustment", don't use Placement New grammar).

You also have the responsibility of the object that is placed. This is done by explicitly calling the destructor:

Void somecode () {char memory [sizeof (fred)]; void * p = memory; fred * f = new (p) fred (); // ... f-> ~ fred (); // Explicit call Destructured function} of the locked object} This is the only timing of explicit call destructor.

Extracted to http://www.sunistudio.com/cppfaq/dtors.html#[11.7]

转载请注明原文地址:https://www.9cbs.com/read-101399.html

New Post(0)