Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create objects in pre-allocated memory

We can use placement new to create an object in pre-allocated memory.

Let's consider the following example:

char *buf  = new char[1000];   //pre-allocated buffer
string *p = new (buf) MyObject();  //placement new 
string *q = new (buf) MyObject();  //placement new

I've created two objects in the pre-allocated buffer. Are the two objects created randomly within the buffer or created in contiguous memory blocks? If we keep creating more objects in the buffer and want them to be stored in contiguous memory blocks, what should we do? Create an array in the buffer first and then create each object in the element slots of the array?

like image 469
Terry Li Avatar asked Nov 28 '11 19:11

Terry Li


People also ask

When object is created the memory is allocated for?

When an object is created, memory is allocated to hold the object properties. An object reference pointing to that memory location is also created. To use the object in the future, that object reference has to be stored as a local variable or as an object member variable. Code section 4.30: Object creation.

How are objects memory allocated?

The memory for that object is allocated by the operating system. The name you declare for the object can then be used to access that block of memory. When you use dynamic memory allocation you have the operating system designate a block of memory of the appropriate size while the program is running.

How do you allocate memory to an object in C++?

When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated. Use the delete operator to deallocate the memory allocated by the new operator. Use the delete[] operator to delete an array allocated by the new operator.

What is allocating memory for objects called?

Correct Option: C. When you allocate memory for an array of objects, the default constructor must be called to construct each object. If no default constructor exists, you're stuck needing a list of pointers to objects.


1 Answers

The two objects are both created at the same memory location, namely buf. This is undefined behaviour (unless the objects are POD).

If you want to allocate several objects, you have to increment the pointer, e.g. buf + n * sizeof(MyObject), but beware of alignment issues

Also don't forget to call destructors when you're done.

like image 89
Kerrek SB Avatar answered Sep 24 '22 07:09

Kerrek SB