What are uses of the C++ construct “placement new”

2019-01-14 03:28发布

I just learned about the C++ construct called "placement new". It allows you to exactly control where a pointer points to in memory. It looks like this:

 #include <new>        // Must #include this to use "placement new"
 #include "Fred.h"     // Declaration of class Fred

 void someCode()
 {
   char memory[sizeof(Fred)];
   void* place = memory;

   Fred* f = new(place) Fred();   // Create a pointer to a Fred(),
                                  // stored at "place"

   // The pointers f and place will be equal

   ...
 } 

(example from C++ FAQ Lite)

In this example, the this pointer of Fred will be equal to place.


I've seen it used in our team's code once or twice. In your experience, what does this construct enable? Do other pointer languages have similar constructs? To me, it seems reminiscent of equivalence in FORTRAN, which allows disparate variables to occupy the same location in memory.

12条回答
我想做一个坏孩纸
2楼-- · 2019-01-14 04:22

seems to me like a way of allocating an object on the stack ..

查看更多
Ridiculous、
3楼-- · 2019-01-14 04:23

I use this construct when doing C++ in kernel mode.

I use the kernel mode memory allocator and construct the object on the allocated chunk.

All of this is wrapped in classes and functions, but in the end I do a placement new.

查看更多
仙女界的扛把子
4楼-- · 2019-01-14 04:25

I've used it to create objects based on memory containing messages received from the network.

查看更多
5楼-- · 2019-01-14 04:29

Placement new can be used to create type-safe unions, such as Boost's variant.

The union class contains a buffer as big as the biggest type it's specified to contain (and with sufficient alignment). It placement news objects into the buffer as required.

查看更多
啃猪蹄的小仙女
6楼-- · 2019-01-14 04:31

Placement new allows the developer to allocate the memory from preallocated memory chunk. If the system is larger, then developers go for using placement new. Now I am working on a larger avionics software there we allocate the large memory that is required for the execution of application at the start. And we use the placement new to allocate the memory wherever required. It increases the performance to some amount.

查看更多
\"骚年 ilove
7楼-- · 2019-01-14 04:32

It can be useful when paging out memory to a file on the hard drive, which one might do when manipulating large objects.

查看更多
登录 后发表回答