Is it possible in C++ to create a new object at a specific memory location? I have a block of shared memory in which I would like to create an object. Is this possible?
You want placement new
(). It basically calls the constructor using a block of existing memory instead of allocating new memory from the heap.
Edit: make sure that you understand the note about being responsible for calling the destructor explicitly for objects created using placement new()
before you use it!
Yes. You need to use placement variant of operator new(). For example:
void *pData = ....; // memory segment having enough space to store A object
A *pA = new (pData) A;
Please note that placement new does not throw exception.
Unfortunately the artivle on c++-faq-lite is BAD.
You need to this:
class Plop { /* STUFF */ };
std::vector<char> buffer(sizeof(Plop));
Plop* p = new (&buffer[0]) Plop(1);
// Do Stuff
p->~Plop();
Advantages of this technique.
- The buffer memory will be reclaimed by RAII when vector is out of scope.
- The memory allocated by buffer is guranteed to be correctly aligned.
- This is guranteed by the standard.
This is because std::vector<> uses new to dynamically allocate the buffer. - The common anti usage is to use a locally declared char[] array.
The problem with this is that the array has no guarantted alignement properties.
This has a tendency to cause crashes when you least expect them and is impossable to debug.
- This is guranteed by the standard.
if you want to allocate a lot of fine-grained objects, the best approach will be to use placement new in conjunction with some sort of a ring buffer. otherwise, you will have to keep track of the pointers aside from the object pointers themselves.