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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With