So I came across placement new recently, and I had a question regarding it. I do understand that placement new is used when you want to allocate an object on an already allocated memory.
Let's say I have a class called foo, which is 20 bytes.
I'd do some operations with it, and then I'll call a placement new for a class called bar, which is 10 bytes.
What happens to the last 10 bytes that is not part of the new object? Does placement new partition only the amount of memory required, which is in this case 10 bytes? Or does the pointer just carry around the extra 10 bytes until it is deallocated?
And another case, let's say I've first started by allocating memory for class bar, which is 10 bytes. I'll then placement new class foo, which is 20 bytes. Will the compiler allocate more memory? Or do I have to make sure to allocate enough memory beforehand?
What happens to the last 10 bytes that is not part of the new object.
Nothing at all. Placement-new does not touch it. It would not know if something else already existed in that block of memory. You could easily allocate size for 2 bar
objects, construct a bar
object in the second 10 bytes, then construct another bar
object in the first 10 bytes. Think of what would happen if placement-new did something to overstep the bounds of the memory address you provide and it corrupted the bar
in the second half of the memory. Not good. So it doesn't do that.
Does placement new partition only the amount of memory required, which is in this case 10bytes?
Yes. Placement-new would simply call the bar
constructor, passing it the specified memory address as the starting address for the constructor to initialize. The constructor would initialize only the portion of the memory it needs. Since the bar
class is 10 bytes, no more than 10 bytes can be initialized. The remaining 10 bytes are untouched.
Or does the pointer just carry around the extra 10 bytes until it is deallocated.
If you allocate 20 bytes and construct a bar
in the first 10 bytes, the remaining 10 bytes would simply exist after the bar
object in memory, but not be part of the bar
object itself. You can do whatever you want with those 10 bytes.
And another case, lets say I've first started of by allocating memory for class bar, which is 10 bytes. I'll then placement new class foo, which is 20 bytes. Will the compiler allocate more memory?
No. Placement-new simply constructs the specified class at the memory address you provide. It is your responsibility to ensure that memory is large enough to hold the class being constructed.
Or do I have to make sure to allocate enough memory beforehand?
Yes.