TITLE: shared memory pool and the new operator KJ = jskim@rose.etri.re.kr (Kim Jungsun) ZX = zqx@siesta.cs.wustl.edu (Zeqing Xia) FH = fjh@munta.cs.mu.OZ.AU (Fergus Henderson), 14 Jul 95 XZ: I would like to know if anyone has experience in create an object from a shared memory area. [...] How can I pass a heap pointer of some sort to let the program know "allocate from this heap"? KJ: Probably the placement syntax new may help. FH: Yes, good suggestion. KJ: The C++ memory allocation scheme provides a way to construct an object in an arbitrary location via a placement syntax. class X { ... } // Define an allocation function using placement syntax void* operator new (size_t sz, void* p) { return p; } FH: You should define that version of placement new yourself - it is part of the standard library. Just #include . KJ: ... void* sp = shm_malloc(sizeof(X)); // Allocate memory in shared memory X* xp = new (sp) X; // Construct an X in the shared memory FH: A better way would be to define class Shared_Memory_Arena {} shared_mem; void* operator new (size_t size, Shared_Memory_Arena&) { return shm_malloc(size == 0 ? 1 : size); } Then you can just write X* xp = new (shared_mem) X; // Allocate and construct an X in // shared memory Note that you should also define void* operator delete (void * pointer, Shared_Memory_Arena&) { shm_free(pointer); } so that the memory will be recovered if the constructor for `X' throws an exception. However, you can't write delete (shared_mem) xp; The C++ committee considered allowing this syntax, but it turns out that there are some technical parsing problems. Instead, you must write xp->~X(); shm_free(xp); Alternatively, you can define template void Delete (Shared_Memory_Arena&, T* p) { p->~T(); shm_free(p); } and then write Delete (shared_mem, xp); KJ: Later, when you want to construct another object at the same place, you must delete a previouly allocated memory by explicitly calling X's destructor like this: xp->X::~X(); FH: Using that syntax is almost certainly a mistake. You should use just the plain xp->~X(); unless you specifically want to suppress the virtualness of a virtual destructor --- and I can't imagine why you would want to do that.