您自己已经回答了这个问题,基本上,当您想创建一个对象并告诉它它应该使用哪个内存地址时,将使用placement new。
Placement new 的典型用法是在共享内存上创建一个对象
来自:
http ://www.drdobbs.com/creating-stl-containers-in-shared-memory/184401639
共享内存中的 C++ STL 容器 想象一下,将 STL 容器(例如映射、向量、列表等)放置在共享内存中。将如此强大的通用数据结构放置在共享内存中,为使用 IPC 共享内存的进程提供了强大的工具。不需要为通过共享内存进行通信而设计和开发特殊的数据结构。此外,STL 的所有灵活性都可以用作 IPC 机制。STL 容器在后台管理自己的内存。当一个项目被插入到 STL 列表中时,列表容器会自动为内部数据结构分配内存来保存插入的项目。考虑将 STL 容器放在共享内存中。容器本身分配其内部数据结构。在堆上构造一个 STL 容器是不可能完成的任务,
进程 A 执行以下操作:
//Attach to shared memory
void* rp = (void*)shmat(shmId,NULL,0);
//Construct the vector in shared
//memory using placement new
vector<int>* vpInA = new(rp) vector<int>*;
//The vector is allocating internal data
//from the heap in process A's address
//space to hold the integer value
(*vpInA)[0] = 22;
Process B does the following:
vector<int>* vpInB =
(vector<int>*) shmat(shmId,NULL,0);
//problem - the vector contains internal
//pointers allocated in process A's address
//space and are invalid here
int i = *(vpInB)[0];